【问题标题】:Using std::bind in std::bind : compilation error (implicit cast) [duplicate]在 std::bind 中使用 std::bind :编译错误(隐式转换)[重复]
【发布时间】: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(&amp;C::step, this) 的结果是 _Bind_helper not @ 987654328@。您需要自己进行转换:bind(&amp;C::work, this,function&lt;bool()&gt;(bind(&amp;C::step1, this)), function&lt;bool()&gt;(bind(&amp;C::step2, this)))Live Example
  • @JonathanMee 这行得通,但不是出于您认为的原因。毕竟std::bind(&amp;C::step1, this) 本身是可转换为std::function&lt;bool()&gt;。
  • @requinham 这绝对是问题所在。并且您编写的测试代码运行良好:ideone.com/tzifGe 可能存在编译器问题,或者您还没有向我展示其他事情。

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


【解决方案1】:

问题在于bind() 会急切地评估嵌套的bind 表达式。因此,您最终不会得到一些返回bool 的可调用对象(正如您从std::bind(&amp;C::step1, this) 所期望的那样),而是最终得到bool。

改为使用 lambda:

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

【讨论】:

  • 我想知道你是否知道这个问题在哪里被引用。 +1
  • @MohamadElghawi 你是什么意思?
  • 您说:“bind() 将急切地评估嵌套的绑定表达式”。只是想知道你在哪里读到的。提前致谢。
  • @Mohamad reference,查看operator()下的行为
  • @MohamadElghawi "(例如,在对 bind 的初始调用中使用了另一个绑定子表达式作为参数),然后该绑定子表达式立即作为具有相同 cv 限定的左值对象调用g,并将其结果传递给可调用对象。” en.cppreference.com/w/cpp/utility/functional/…
猜你喜欢
  • 1970-01-01
  • 2016-11-13
  • 2012-04-29
  • 2013-09-01
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-04
相关资源
最近更新 更多