C++ 如何绑定、存储和执行std::function对象?
我想用参数绑定一个函数,将其存储在队列中,稍后再执行。迄今为止的守则:C++ 如何绑定、存储和执行std::function对象?,c++,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
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);
};
structfoo{
...
使某些函数无效(int);
...
};
Foo:另一个_函数(){
//获取bar的实例
Bar*Bar=Environment->getBar();
//绑定函数
std::functionadd(func);
};
类栏中队列的原型如下所示
std::queue<std::function<void<const Foo&, int>> jobs;
std::queue一些函数的原型是:
void Foo::some_function(int);
让我们检查一下这个表达式:
std::bind(&Foo::some_function, this, 42)
表达式所做的是创建一个可调用对象,我们称之为B
。调用B
时,它将调用Foo::some_函数
,参数绑定到this
和42
。由于这将绑定Foo::some_函数的所有参数
,因此B
没有剩余参数。因此,B
调用的函数类型是void()
换句话说,您的std::function
类型错误<代码>作业
应按以下方式键入:
std::queue<std::function<void()> jobs;
std::queue一些函数的原型是:
void Foo::some_function(int);
让我们检查一下这个表达式:
std::bind(&Foo::some_function, this, 42)
表达式所做的是创建一个可调用对象,我们称之为B
。调用B
时,它将调用Foo::some_函数
,参数绑定到this
和42
。由于这将绑定Foo::some_函数的所有参数
,因此B
没有剩余参数。因此,B
调用的函数类型是void()
换句话说,您的std::function
类型错误<代码>作业
应按以下方式键入:
std::queue<std::function<void()> jobs;
std::queue如果要存储无参数可调用的函数,则存储函数的类型不能有参数。如果要存储无参数可调用的函数,则存储函数的类型不能有参数。我真傻!谢谢你的回答!愚蠢的我!谢谢你的回答!