Std :: function and shared_ptr

I used Loki Functor for a while, and I recently asked a question about it (still haven't answered ...) I was told to use std :: function, but I prefer the Loki Functor implementation, since it also works with all types of pointers as parameters (e.g. 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); } 

Is there a way to do this with std :: function?

+7
c ++ std-function loki
source share
3 answers

Use std::bind .

 auto func = std::bind(&Toto::foo, ptr, std::placeholders::_1); 

here func will be output to the type that was returned from std::bind , or if you don't like auto , you can use (and you want to use std::function )

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

Here std::function will be built from the result of std::bind . ptr will be copied to some object returned from std::bind , however you can use std::ref / std::cref if you do not want to copy.

+6
source share

Use std::bind .

 struct Toto { void foo( int param ) { std::cout << "foo: " << param << std::endl; } }; int main() { std::shared_ptr<Toto> ptr = std::make_shared<Toto>(); std::function< void(int) > func( std::bind( &Toto::foo, std::bind( [ptr] () { return ptr.get(); } ), std::placeholders::_1 ) ); func( 1 ); } 

Live demo.

Edit: An internal bind with a lambda expression is not actually needed, but I will just leave it here as an illustration of a more advanced use.

+1
source share

If you do not want to use std::bind , the option should use the lambda function, which leads to even less code, and I personally find it more intuitive:

 auto func = [&ptr](int p){ ptr->foo(p); }; 

or without auto :

 std::function<void(int)> func = [&ptr](int p){ ptr->foo(p); }; 

But this only works if the fixed function (i.e. &Toto::foo not passed dynamically). If not, this is possible with lambda, but you need a slightly different syntax, and std::bind may be more attractive again.

+1
source share

All Articles