Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member function call on shared_ptr through member function pointer in template

Tags:

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?

like image 671
Meena Alfons Avatar asked Nov 16 '16 08:11

Meena Alfons


People also ask

Can we call member function using this pointer?

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.

How do you access member functions using pointers?

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.

What is the purpose of the shared_ptr <> template?

std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer.

Is shared_ptr a smart 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.


1 Answers

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

like image 129
songyuanyao Avatar answered Sep 19 '22 15:09

songyuanyao