如何绑定、存储和执行std::函数对象

How to bind, store and execute a std::function object?

本文关键字:执行 std 存储 函数 对象 何绑定 绑定      更新时间:2023-10-16

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

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();
} 

所以,这个错误对我来说似乎很清楚(编译器如何知道存储的对象实际上是一个带参数的对象,因此不需要参数),但我不知道如何处理这个问题。我也想知道如果传递'this'到绑定可能不会导致在以后的时间点,例如,如果对象不再存在。

提前感谢!迈克尔。

注::这里已经有一个类似主题的帖子了,但是没有多大帮助

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()>