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

时间:2016-05-27 11:17:38

标签: c++ c++11 std stdbind

当我想创建一个用于包装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));
                                                                        ^

1 个答案:

答案 0 :(得分:7)

问题是bind()会急切地评估嵌套的bind表达式。因此,不是最终返回一些返回bool的callable(正如您在std::bind(&C::step1, this)中所预期的那样),而是最终得到bool

相反,请使用lambdas:

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