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?
You can use pointers to member functions in the same manner as pointers to functions. You can compare pointers to member functions, assign values to them, and use them to call member functions.
To access a member function by pointer, we have to declare a pointer to the object and initialize it (by creating the memory at runtime, yes! We can use new keyboard for this). The second step, use arrow operator -> to access the member function using the pointer to the object.
std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer.
The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.
std::shared_ptr
doesn't support pointer-to-member access operator (i.e. ->*
and .*
). So we can't invoke member function pointers 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With