C ++ 0x std :: function as method argument

I am trying to pass a std :: function using a method like this:

class dispatch { public: deliver( std::function<void ( void )> task ); } 

This works as expected. However, I want to pass arguments to some of the methods set as a task, but would prefer not to create overloads for all the various functions <...>.

for example, it’s generally possible to just create a method like the following

 deliver( std::function& task ); 

and just call

 dispatch->deliver( bind( &Object::method, X ) ); 

or

 dispatch->deliver( bind( &Object::method, X, arg1, arg2 ) ); 

etc...

Thanks for every contribution. It would seem that my real mistake is sending calls -> deliver with an additional argument, which is also a binding call.

 dispatch->deliver( bind( &Object::method1, X1, bind( &Object::method1, X2 ) ); 

error: / usr / include / C ++ / v1 / functional: 1539: 13: error: there is no corresponding function to call '__mu_expand' return __mu_expand (__ ti, __uj, __indices ());

+7
source share
3 answers

std::function<void(void)> already polymorphic, as is its entire point. Thus, these last two fragments will work (as long as the returned bind functor can be called without arguments and, of course, returns nothing) without changing what you already have.

+9
source

Yes, it is possible if you use bind to create compatible function objects:

 #include <boost/bind.hpp> #include <boost/function.hpp> #include <iostream> #include <list> #include <string> typedef boost::function<void(void)> fun_t; typedef std::list<fun_t> funs_t; void foo() { std::cout <<"\n"; } void bar(int p) { std::cout<<"("<<p<<")\n"; } void goo(std::string const& p) { std::cout<<"("<<p<<")\n"; } void caller(fun_t f) { f(); } int main() { funs_t f; f.push_front(boost::bind(foo)); f.push_front(boost::bind(bar, int(17))); f.push_front(boost::bind(goo, "I am goo")); for (funs_t::iterator it = f.begin(); it != f.end(); ++it) { caller(*it); } return 0; } 

(Note that I am using Boost.Function and Boost.Bind, but there should be no difference in using std :: bind and std :: function.)

+3
source
 class dispatch { public: template <typename ... Params> deliver( std::function<void (Params && p...)> task, Params && p ) { task(std::forward(p)...); } }; 

I did not compile this (corrections are welcome!), But the idea should work.

 dispatch->deliver( bind( &Object::method, X ) ); dispatch->deliver( bind( &Object::method, X, arg1, arg2 ) ); // OR! dispatch->deliver( bind( &Object::method, X ), arg1, arg2 ); 

The only thing I don’t understand is how this happens if the Object::method has default parameters instead of overloads.

+1
source

All Articles