std :: function和shared_ptr

Ath*_*ase 7 c++ loki std-function

我一直在使用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_ptr<Toto> ptr = std::make_shared<Toto>();

    Loki::Functor<void, LOKI_TYPELIST_1(int)> func( ptr, &Toto::foo );

    func(1);
}
Run Code Online (Sandbox Code Playgroud)

有没有办法用std :: function做到这一点?

For*_*veR 6

使用std::bind.

auto func = std::bind(&Toto::foo, ptr, std::placeholders::_1);
Run Code Online (Sandbox Code Playgroud)

在这里,func将推断出类型,从中返回std::bind或如果你不喜欢auto你可以使用(并且你想使用std::function)

std::function<void(int)> func = std::bind(&Toto::foo, 
ptr, std::placeholders::_1);
Run Code Online (Sandbox Code Playgroud)

这里std::function将根据结果构建std::bind. ptr将被复制到从中返回的某个对象std::bind,但是如果您不想要复制,则可以使用std::ref/ std::cref.