如何将 boost::signal2::signal 连接到纯虚函数

How to connect a boost::signal2::signal to a pure virtual function?

本文关键字:函数 连接 signal2 boost signal      更新时间:2023-10-16

我在组件中使用boost::signals2::signalsUpdateComponent . 此组件的特定聚合的类型为 Updateable 。我希望Updateable能够连接到UpdateComponentboost::signals2::signal。 我应该指出,Updateableslotpure-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);
}

我收到以下两个错误:

  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(效果很好(的原因是:我不希望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));
}