[英]How to bind, store and execute a std::function object?
I want to bind a function with arguments, store it in a queue and execute it later. 我想将一个函数与参数绑定,将其存储在队列中,然后再执行。 The code so far:
到目前为止的代码:
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);
};
The prototype of the queue in class Bar looks like Bar类中队列的原型看起来像
std::queue<std::function<void<const Foo&, int>> jobs;
However, if I'm going to execute the object stored in queue I get an error about missing arguments. 但是,如果我要执行存储在队列中的对象,则会收到有关缺少参数的错误。 The code for executing stored objects
执行存储对象的代码
Bar::worker(){
std::function<void<const Foo&, int> job:
{
...
job = jobs.front();
jobs.pop();
...
}
job();
}
So, the error seems pretty clear to me (how should the compiler know that the stored object is actually one with arguments and therefore doesn't need ones), but I don't know how to handle this. 因此,错误对我来说似乎很清楚(编译器应如何知道存储的对象实际上是带有参数的对象,因此不需要参数),但我不知道如何处理。 I'm also wondering if passing the 'this' to the bind might not cause at a later point of time, eg if the object doesn't exist anymore.
我还想知道是否可能在以后的某个时间点将'this'传递给绑定,例如,如果该对象不再存在。
Thanks in advance! 提前致谢! Michael
麦可
PS: There is already an thread with a similiar topic on that, over here , but it didn't help much PS:已经有与上一个类似的话题,在一个线程在这里 ,但它并没有太大的帮助
The prototype of some_function
is: some_function
的原型是:
void Foo::some_function(int);
Let's examine this expression: 让我们检查一下这个表达式:
std::bind(&Foo::some_function, this, 42)
What the expression does is create a callable object, let's call it B
. 表达式的作用是创建一个可调用对象,我们称其为
B
When B
is called, it will call Foo::some_function
, with the arguments bound to this
and 42
. 调用
B
,它将调用Foo::some_function
,并将参数绑定到this
和42
。 Since this binds all of the parameters of Foo::some_function
, there are no parameters left for B
. 因为这绑定了
Foo::some_function
所有参数,所以B
没有剩余的参数。 Therefore, the function type of B
's invocation is void ()
. 因此,
B
的调用的函数类型为void ()
。
In other words, your std::function
is of the wrong type. 换句话说,您的
std::function
类型错误。 jobs
should be typed like this: jobs
应该像这样输入:
std::queue<std::function<void()> jobs;
And of course func
should be typed as std::function<void()>
as well. 当然,
func
也应键入std::function<void()>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.