【发布时间】:2016-05-27 11:17:38
【问题描述】:
当我想创建一个 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));
^
【问题讨论】:
-
绑定的绑定很神奇。它不像你想象的那样工作。
-
使用 lambdas 代替 bind。
-
您的编译器错误语句告诉您问题所在,
bind不进行隐式转换,bind(&C::step, this)的结果是_Bind_helpernot @ 987654328@。您需要自己进行转换:bind(&C::work, this,function<bool()>(bind(&C::step1, this)), function<bool()>(bind(&C::step2, this)))Live Example -
@JonathanMee 这行得通,但不是出于您认为的原因。毕竟
std::bind(&C::step1, this)本身是可转换为std::function<bool()>。 -
@requinham 这绝对是问题所在。并且您编写的测试代码运行良好:ideone.com/tzifGe 可能存在编译器问题,或者您还没有向我展示其他事情。