2016-05-27 12 views
4

作業(..)メンバーをラップするためのstd ::関数を作成したいとき、コンパイルエラーが発生しました。std :: bindをstd :: bindで使用する:コンパイルエラー(暗黙のキャスト)

サンプルコード:

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;} 
}; 

コンパイルエラー:事前 /requinhamで

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)); 
                     ^

おかげ

+2

バインドは魔法です。期待通りに機能しません。 –

+3

バインドの代わりにlambdasを使用します。 – Yakk

+1

あなたのコンパイラのエラーステートメントは、 'bind'は暗黙の変換を行わず、' bind(&C :: step、this) 'の結果は' _Bind_helper' *ではなく 'function 'です。 'bind(&C :: step2、this)));あなたは変換を自分で行う必要があります:' bind(&C :: work2、this、function (bind(&C :: step1、this))、function ](http://ideone.com/lvVL5z) –

答えて

7

問題はbind()が熱心にネストされたbind式を評価することです。したがって、boolstd::bind(&C::step1, this)から意図した通り)を返す呼び出し可能コードで終わるのではなく、boolになります。

代わりに、ラムダを使用します。バインドの

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

この問題がどこで参照されているのか分かりましたか? +1 –

+0

@MohamadElghawiあなたはどういう意味ですか? – Barry

+0

あなたは言った: "bind()は熱心にネストされたバインド式を評価する"。あなたがそれをどこで読んでいるのか不思議でした。前もって感謝します。 –

関連する問題