When I want to create an std::function for wrapping work(..) member, I had a compilation error that tired me.
sample code :
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;}
};
Compile Error:
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));
^
The problem is that bind()
will eagerly evaluate nested bind
expressions. So instead of ending up with some callable that returns bool
(as you had intended from std::bind(&C::step1, this)
), you just end up with bool
.
Instead, use lambdas:
std::function<void(void) > f = [this]{
work([this]{ return step1(); },
[this]{ return step2(); });
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With