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

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

本文关键字:std bind 转换 编译 错误      更新时间:2023-10-16

当我想创建一个 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(); });
};