gpt4 book ai didi

c++ - 如何将 boost::signals2::signal 连接到纯虚函数?

转载 作者:搜寻专家 更新时间:2023-10-31 00:43:30 25 4
gpt4 key购买 nike

我正在使用 boost::signals2::signals在组件中,UpdateComponent .此组件的特定聚合类型为 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));
}

关于c++ - 如何将 boost::signals2::signal 连接到纯虚函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10472216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com