c ++ 0x std :: function作为方法参数

时间:2011-10-26 22:30:01

标签: c++ function bind c++11

我试图通过类似的方法传递std :: function:

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

这可以按预期工作。但是我希望将参数传递给作为任务提供的一些方法,但是不希望为所有不同的函数创建重载&lt; ...&gt;形式。

例如,只是为了创建一个类似下面的方法

deliver( std::function& task );

,只需使用

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

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

等...

感谢大家的投入。看起来我真正的错误是调用dispatch-&gt;传递附加参数也是绑定调用。

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

错误:/ usr / include / c ++ / v1 / functional:1539:13:错误:没有用于调用'__mu_expand'的匹配函数       return __mu_expand(__ ti,__ uj,__ indices());

3 个答案:

答案 0 :(得分:10)

std::function<void(void)>已经是多态的,这就是它的重点。因此,这两个最后的片段将起作用(只要函数bind返回可以不带参数调用,当然不返回任何内容),而不会更改已有的内容。

答案 1 :(得分:3)

是的,只要您使用bind生成兼容的函数对象就可以了:

#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;
}

(注意,我使用Boost.Function和Boost.Bind,但使用std :: bind和std :: function应该没有区别。)

答案 2 :(得分:1)

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

我没有编译过这个(更正欢迎!),但这个想法应该有用。

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

我不清楚的一件事是,如果Object::method默认了params而不是重载,这会是怎么回事。