使用 C 指针,我可以做到这样:
#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
如果我想使用smart_ptr代替C指针,我会遇到编译错误:
error: no operator "->*" matches these operands
operand types are: std::shared_ptr<Foo> ->* void (Foo::*)()
(foo_sptr->*bar_ptr)();
有没有一种方法可以在不使用std :: shared_ptr :: get()的情况下使其工作?
std::function
的在线演示:http://ideone.com/vKsvXA - Tiago Gomesshared_ptr
调用成员函数。 - Angew is no longer proud of SOstd::function
中。虚函数调用在其调用中。 - Angew is no longer proud of SO