Meena Alfons Meena Alfons - 16 days ago 7
C++ Question

Call member function template parameter on shared_ptr

This is a template function that takes a pointer (or a pointer like object) and a member function:

template <typename Ptr, typename MemberFunctor>
int example(Ptr ptr, MemberFunctor func )
{
return (ptr->*func)();
}


If works when used with ordinary pointer:

struct C
{
int getId() const { return 1; }
};

C* c = new C;
example(c, &C::getId); // Works fine


But it does not work with smart pointers:

std::shared_ptr<C> c2(new C);
example(c2, &C::getId);


Error message:

error: C2296: '->*' : illegal, left operand has type 'std::shared_ptr<C>'


Why? and How to make something that works with both?

Answer

std::shared_ptr doesn't support pointer-to-member access operator (i.e. ->* and .*). So we can't call member function with ->* on it directly. You can change the invoking syntax to use operator* and operator.*, which works for both raw pointers and smart pointers.

template <typename Ptr, typename MemberFunctor>
int example(Ptr ptr, MemberFunctor func )
{
    return ((*ptr).*func)();
}

LIVE

Comments