如何绑定、存储和执行std::函数对象
How to bind, store and execute a std::function object?
我想用参数绑定一个函数,将其存储在队列中并稍后执行。目前的代码:
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
,参数将绑定到this
和42
。因为这绑定了Foo::some_function
的所有参数,所以没有为B
留下任何参数。因此,B
调用的函数类型为void ()
。
换句话说,您的std::function
是错误的类型。jobs
应该这样输入:
std::queue<std::function<void()> jobs;
当然func
也应该写成std::function<void()>
相关文章:
- 在C++中对T*类型执行std::move的意外行为
- 专用于 std 元组的模板,而无需用户执行remove_cvref
- 没有执行策略的 std::transform_reduce 是可移植的吗?
- 将 int 转换为双精度以执行 std::complex <double>的"*"操作
- 执行 std::min(0.0, 1.0) 和 std::max(0.0, 1.0) 会产生未定义的行为
- 在成员变量上执行std :: upper_bound的任何方法
- 在执行std::函数析构函数时调用它
- 无法正确执行STD ::排序
- C 编译器如何在延期和异步执行std :: async之间进行选择
- 使用 GCC 4.8 编译时无法对向量执行 std::swap
- 在每种情况下都执行“std::set”对元素进行排序
- 执行std::string::clear回收与字符串关联的内存
- 如何通过 C++ boost::序列化执行 std::map 的部分反序列化
- 在单步执行 std::function 调用时,如何跳过 std 命名空间中的方法调用?(使用 GDB
- 在 AllocConsole 之前执行 std::endl 会导致不显示 std::cout
- 如何在constchar*上执行std::find
- 执行std::thread::join()时的SIGINT
- 在执行std::函数对象时重新分配该对象
- 执行 std::元组和 std::p air 支持聚合初始化
- 如何绑定、存储和执行std::函数对象