简体   繁体   中英

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

I am using boost::signals2::signals in a component, UpdateComponent . A specific aggregate for this component is of type Updateable . I would like Updateable to be able to connect to UpdateComponent 's boost::signals2::signal . I should note that the Updateable 's slot is pure-virtual .

Below is a concrete example of the code:

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

At some point in UpdateComponent 's code, I perform onUpdate(myFloat) ; I believe this is akin to "firing" the boost::signals2::signal to all of its "listeners".

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

In Updateable 's constructor, I do the following:

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

I receive the following two errors:

  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&)'

I should mention I am using Qt in conjunction with boost. However, I have added CONFIG += no_keywords to my .pro file, so the two should be work together smoothly, as outlined on the boost website. The reason I don't use Qt's signals and slots (which works very well) is: I do not want Updateable to be a QObject .

If someone could help me figure out why I am getting an error, it would be greatly appreciated!

The slot you are passing to connect must be a functor. To connect to a member function, you can use either boost::bind or C++11 lambda . For example using lambda:

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

or using bind :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM