Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using std::shared_ptr with a pointer to member function

Tags:

c++

pointers

With C pointers I can do somethnig 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 a 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() ?

like image 582
MagunRa Avatar asked Dec 26 '22 13:12

MagunRa


1 Answers

std::shared_ptr does not provide an overloaded operator ->*. So you have to use get():

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

Live example

like image 120
Angew is no longer proud of SO Avatar answered Jan 06 '23 20:01

Angew is no longer proud of SO