Non-type template function pointer to const member function

心已入冬 提交于 2019-12-05 14:38:11

I think you might be able to address this by removing the function pointer from the template type signature and instead relying on overloading:

template <class C>
    void Call(C* ptr, void (C::*function)()) {
    (ptr->*function)();
}
template <class C>
    void Call(C* ptr, void (C::*function)() const) {
    (ptr->*function)();
}

This now uses normal function overloading to select which of the two functions should be called. const member function pointers will call down to the second version, while non-const functions will call up to the first version. This also means that you don't need to explicitly provide any type information to the template function; the compiler can deduce C in both contexts.

Let me know if (1) this doesn't work or (2) this does work, but isn't what you want.

Hope this helps!

Use std::bind or lambdas, which VS2010 supports, and std::function and this will cease to be a problem for you.

Your problem is that a member function pointer is a different type than a const member function pointer. I modified your Call function to this:

template< typename C, typename funcptr_t, funcptr_t ptr >
void Call( C *instance )
{
  (instance->*ptr)();
}

and now using the additional template parameter, I can call it like this:

Call<foo,void (foo::*)(),&foo::MemberFunction>(&bar);
Call<foo,void (foo::*)() const, &foo::ConstMemberFunction>(&bar);

That's a bit messy, though. The overloading solution is better! :-)

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