About shared_ptr and pointer to member operator `->*` and `std::bind`

ⅰ亾dé卋堺 提交于 2019-11-29 03:58:24
Alice

In a nut shell: yes std::bind is a replacement for member function pointers.

Why? because member function pointers are awful, and their only purposes is to implement delegates, which is why std::bind and std::function do

For reference on how member function pointers are implemented, see my previous answer here. In simplest terms, member function pointers are crippled by the standard because they do not allow for calls after casts; this makes them quite pointless for the sort of behavior 90% of people want from member function pointers: delegates.

For this reason, std::function is used to represent an abstract "callable" type, with std::bind being used to bind a this to the member function pointer. You should absolutely not mess with member function pointers, and instead use std::bind and std::function.

I believe the simplest soultion would be to replace 'structure dereference' (->) operator with a pair of derefence(*) and structure reference(.) operators:

template <typename Pointer, typename Function, typename... Args>
auto invoke1(Pointer p, Function f, Args... args) -> decltype(((*p).*f)(args...))
{
  return ((*p).*f)(args...);
}

I believe shared_ptr does not have operator ->* because it's impossible to implement it for arbitrary number of arguments (which C++11 allows to do for other use cases). Also, you can easily add an overload of invoke function for smart pointers that calls get(), so complicating the interface is not desirable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!