Using std :: shared_ptr with a pointer to a member function

Using C pointers, I can do something like this:

#include <iostream>
#include <memory>
class Foo {
     void bar(){
     std::cout<<"Hello from Foo::bar \n";
        }
   } 

void main(){
    Foo foo; 
    Foo* foo_ptr=&foo;
    std::shrared_ptr<Foo> foo_sptr(&foo);
    void (Foo::*bar_ptr)()=&Foo::bar;
    (foo.*bar_ptr)();
    (foo_ptr->*bar_ptr)();
    //(foo_sptr->*bar_ptr)(); // does not compile for me

If I want to use smart_ptr instead of a C pointer, I get a compiler error:

error: no operator "->*" matches these operands
        operand types are: std::shared_ptr<Foo> ->* void (Foo::*)()
(foo_sptr->*bar_ptr)();

Is there a way to make this work without std :: shared_ptr :: get ()?

+3
source share
2 answers

std::shared_ptrdoes not provide overload operator ->*. Therefore you should use get():

(foo_sptr.get()->*bar_ptr)();

Living example

+9
source
(&*foo_sptr)->*bar_ptr()

It's a little ugly to watch, but it will work for both shared_ptr and raw pointers.

0
source

All Articles