2012-05-06 36 views
2

我在組件UpdateComponent中使用boost::signals2::signals。該組件的具體聚合類型爲Updateable。我希望Updateable能夠連接到UpdateComponentboost::signals2::signal。我應該注意到Updateableslotpure-virtual如何將boost :: signal2 :: signal連接到純虛函數?

下面是代碼的一個具體的例子:

// This is the component that emits a boost::signals2::signal. 
class UpdateComponent { 
    public: 
     UpdateComponent(); 
     boost::signals2::signal<void (float)> onUpdate; // boost::signals2::signal 
} 

UpdateComponent的代碼的某一點,我執行onUpdate(myFloat);我相信這類似於將「boost::signals2::signal」「解僱」給它的所有「聽衆」。

// The is the aggregate that should listen to UpdateComponent's boost::signals2::signal 
class Updateable { 
    public: 
     Updateable(); 
    protected: 
     virtual void onUpdate(float deltaTime) = 0; // This is the pure-virtual slot that listens to UpdateComponent. 
     UpdateComponent* m_updateComponent; 
} 

Updateable的構造,我做到以下幾點:

Updateable::Updateable { 
    m_updateComponent = new UpdateComponent(); 
    m_updateComponent->onUpdate.connect(&onUpdate); 
} 

我收到以下兩個錯誤:

  1. ...Updateable.cpp:8: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say '&BalaurEngine::Traits::Updateable::onUpdate' [-fpermissive]
  2. /usr/include/boost/function/function_template.hpp:225: error: no match for call to '(boost::_mfi::mf1<void, BalaurEngine::Traits::Updateable, float>) (float&)'

我應該提到我正在使用Qt與boost。但是,我已將CONFIG += no_keywords添加到我的.pro文件中,因此兩者應該順利合作,如boost網站上所述。我不使用Qt的signalsslots(它工作得很好)的原因是:我不希望UpdateableQObject

如果有人能幫我弄清楚爲什麼我得到一個錯誤,將不勝感激!

+1

,我不能舉一個具體的例子,因爲我不爲信號和槽使用提升,但我可以告訴你,這個問題是因爲你試圖連接到一個非靜態成員函數,它隱式地將一個指向對象的指針作爲參數。谷歌搜索表明,使用'boost :: bind'是做到這一點的方法。 – tmpearce

+0

謝謝,tmpearce。正如irobot下面所說,這是我的問題的原因。 – Alex

回答

5

您傳遞給connect的插槽必須是仿函數。要連接到成員函數,您可以使用boost::bind或C++ 11 lambda。例如使用lambda:

Updateable::Updateable { 
    m_updateComponent = new UpdateComponent(); 
    m_updateComponent->onUpdate.connect(
     [=](float deltaTime){ onUpdate(deltaTime); }); 
} 

或使用bind

Updateable::Updateable { 
    m_updateComponent = new UpdateComponent(); 
    m_updateComponent->onUpdate.connect(
     boost::bind(&Updateable::onUpdate, this, _1)); 
} 
+0

謝謝你,irobot。我不知道這一點。 – Alex

+1

好吧,如果它按照你的方式工作,它會很好! – irobot

+0

是的!我被Qt的SIGNALS和SLOTS宏所破壞(類似的語法),我承認,這使得生活更加愉快。然而,使用Qt的SIGNALS和SLOTS意味着你必須從QObject繼承,這會膨脹一個給定的類。再次感謝irobot的幫助。 – Alex