在 std::bind 中使用 std::bind :编译错误(隐式强制转换)
Using std::bind in std::bind : compilation error (implicit cast)
当我想创建一个 std::function 来包装 work(..) 成员时,我遇到了一个编译错误,让我感到疲倦。
示例代码:
class C{
public:
C(){
std::function<void(void) > f = std::bind(&C::work,
this,
std::bind(&C::step1, this),
std::bind(&C::step2, this));
QList<decltype(f)> lst;
lst.append(f);
.....
}
private:
void work(std::function<bool()> fn1, std::function<bool()> fn2 ) {
if (fn1()) {
QTimer::singleShot(1, fn2);
}
else {
QTimer::singleShot(5, fn1);
}
}
bool step1(){return true;}
bool step2(){return true;}
};
编译错误:
main.cpp:49: erreur : conversion from 'std::_Bind_helper<false, void (C::*)(std::function<bool()>, std::function<bool()>), C* const, std::_Bind<std::_Mem_fn<bool (C::*)()>(C*)>, std::_Bind<std::_Mem_fn<bool (C::*)()>(C*)> >::type {aka std::_Bind<std::_Mem_fn<void (C::*)(std::function<bool()>, std::function<bool()>)>(C*, std::_Bind<std::_Mem_fn<bool (C::*)()>(C*)>, std::_Bind<std::_Mem_fn<bool (C::*)()>(C*)>)>}' to non-scalar type 'std::function<void()>' requested
std::bind(&C::step2, this));
^
问题是bind()
会急切地计算嵌套的bind
表达式。因此,与其以一些返回bool
的可调用对象结束(正如您从 std::bind(&C::step1, this)
中打算的那样),不如以 bool
结束。
相反,请使用 lambdas:
std::function<void(void) > f = [this]{
work([this]{ return step1(); },
[this]{ return step2(); });
};
相关文章:
- 使用 std::应用于 std::bind
- PCL:当我在setConditionFunction中使用std::bind 时,没有合适的转换函数
- std::bind on statd::array 的运算符 []
- std::bind c++ in if statement
- std::bind 是否实现了 std::ref 和 std::cref 来消除函数调用的歧义?
- C++ 事件管理器的回调,使用 std::function 和 std:bind 以及派生类作为参数
- 试图克服 std::bind 编译错误
- c++ std::bind within function
- std::bind to void* to std::function
- std::bind 和 std::函数术语不值为接受 0 个参数?
- 在调用 std::bind 的产品后意外调用析构函数
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 我们应该在使用 std::bind 应用之前检查一个不为空的函数吗?
- 为什么 std::bind 静态类型检查传递给函数的参数?
- 对函数库中的语法感到困惑 std::bind
- 在模板类成员上使用 std::bind
- 如何将参数从函数传递给 std::bind
- 如何在C++中使用 std::bind 函数作为信号处理程序?
- std::bind() 参数列表中函子的执行顺序(可能与函数参数的求值顺序无关)
- 在模板函数参数中使用 std::bind