我一直在使用Loki的Functor,我最近问了一个关于它的问题(仍然没有答案......)我被告知要使用std :: function,但我更喜欢Loki的Functor实现,因为它也适用于各种各样的指针作为参数(例如std :: shared_ptr).
struct Toto { void foo( int param ) { std::cout << "foo: " << param << std::endl; } }; int main( int argc, const char** argv ) { std::shared_ptrptr = std::make_shared (); Loki::Functor func( ptr, &Toto::foo ); func(1); }
有没有办法用std :: function做到这一点?
使用std::bind
.
auto func = std::bind(&Toto::foo, ptr, std::placeholders::_1);
在这里,func
将推断出类型,从中返回std::bind
或如果你不喜欢auto
你可以使用(并且你想使用std::function
)
std::function<void(int)> func = std::bind(&Toto::foo, ptr, std::placeholders::_1);
这里std::function
将根据结果构建std::bind
.
ptr
将被复制到从中返回的某个对象std::bind
,但是如果您不想要复制,则可以使用std::ref
/ std::cref
.