如何绑定,存储和执行std :: function对象?

时间:2014-03-20 12:06:55

标签: c++

我想用参数绑定一个函数,将它存储在队列中并稍后执行。到目前为止的代码:

struct Foo {
    ...
    void some_function(int);
    ...
};


Foo:another_function(){ 
     // get the instance of bar
     Bar* bar = Environment->getBar();
     // bind the function
     std::function<void<const Foo&, int> func  = 
        std::bind(&Foo::some_function, this, 42);
     // add it to bar
     bar->add(func);
};

Bar类中队列的原型看起来像

std::queue<std::function<void<const Foo&, int>> jobs;

但是,如果我要执行存储在队列中的对象,我会收到有关缺少参数的错误。执行存储对象的代码

Bar::worker(){
    std::function<void<const Foo&, int> job:


    {
        ...
        job = jobs.front();
        jobs.pop();
        ...
    }


    job();

} 

所以,错误对我来说似乎很清楚(编译器应该如何知道存储的对象实际上是一个带参数的对象,因此不需要),但我不知道如何处理这个。我也想知道是否通过了这个&#39;这个&#39;绑定可能不会在稍后的时间点引起,例如如果物体不再存在。

提前致谢!  迈克尔

P.S。:在here上已经有一个类似主题的主题,但它没有多大帮助

1 个答案:

答案 0 :(得分:6)

some_function的原型是:

void Foo::some_function(int);

让我们看看这个表达式:

std::bind(&Foo::some_function, this, 42)

表达式的作用是创建一个可调用对象,让我们称之为B。调用B后,它会调用Foo::some_function,参数绑定this42。由于这会绑定Foo::some_function的所有参数,因此B没有剩余参数。因此,B调用的函数类型为void ()

换句话说,您的std::function类型错误。 jobs应该输入如下:

std::queue<std::function<void()> jobs;

当然func也应该输入std::function<void()>

相关问题