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() ?
std::shared_ptr
does not provide an overloaded operator ->*
. So you have to use get()
:
(foo_sptr.get()->*bar_ptr)();
Live example
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