在 std::bind 中使用 std::bind :编译错误(隐式转换)

Using std::bind in std::bind : compilation error (implicit cast)

当我想为 wrapping work(..) 成员创建一个 std::function 时,我遇到了一个让我很累的编译错误。

示例代码:

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 表达式。因此,不是以 returns bool 的某些可调用函数结束(正如您从 std::bind(&C::step1, this) 中预期的那样),而是以 bool 结束。

改为使用 lambda:

std::function<void(void) > f = [this]{
    work([this]{ return step1(); },
         [this]{ return step2(); });
};