我在组件中使用boost::signals2::signals
,UpdateComponent
. 此组件的特定聚合的类型为 Updateable
。我希望Updateable
能够连接到UpdateComponent
的boost::signals2::signal
。 我应该指出,Updateable
的slot
是pure-virtual
。
下面是代码的具体示例:
// 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);
}
我收到以下两个错误:
-
...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]
-
/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的signals
和slots
(效果很好(的原因是:我不希望Updateable
成为QObject
。
如果有人能帮助我弄清楚为什么我会出现错误,将不胜感激!
您要传递给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));
}