gpt4 book ai didi

c++ - 通过 boost 信号 2 的观察者模式

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:23:02 25 4
gpt4 key购买 nike

所以,我已经阅读了 Boost.Signal2 的文档,并且进行了一些谷歌搜索,但我还没有完全找到我需要的东西。我拥有的是一个 Controller 和一个 View 概念。 Controller 将向 View 发送数据以供其呈现。我想要的是我的 Controller 调用 Controller::Update 并在 View 中触发 OnUpdate 函数。

  • Controller 和 View 应该是分离的
  • 可以发出 Controller 上的信号以在 View 中执行 Slots

这是我到目前为止尝试过的代码:

class Listener {
public:
virtual void OnUpdate() {};
};

class View :Listener
{
public:
View(void);
~View(void);
virtual void OnUpdate() override;
};

void View::OnUpdate()
{
std::cout << "Updating in View";
}

class Controller
{
public:
Controller(void);
~Controller(void);
void Update();
};

Controller::Controller(void)
{
// Signal with no arguments and a void return value
boost::signals2::signal<void ()> sig;
sig.connect(boost::bind(&Listener::OnUpdate, this, _1));
// Call all of the slots
sig();
system("pause");
}

这不会编译。我收到error C2825: 'F': must be a class or namespace when followed by '::',但这只是因为我使用 bind 不正确。

有人知道我如何使用 boost 的信号/槽实现我想要的吗?

最佳答案

这里有很多误解。我建议您从更简单的开始。

  • Listener 基类可能需要一个虚拟析构函数
  • 您不能将 Listener::OnUpdate 绑定(bind)到 Controller 类中的 this,因为 Controller 不是派生自监听器
  • 您需要从Listener
  • 公开派生
  • 没有参数,因此您需要传递零占位符(_1 不合适)

这是一个简单的修复示例

Live On Coliru

#include <boost/signals2.hpp>
#include <iostream>

class Listener {
public:
virtual ~Listener() = default;
virtual void OnUpdate() = 0;
};

class View : public Listener
{
public:
View() = default;
~View() = default;
virtual void OnUpdate() override {
std::cout << "Updating in View\n";
}
};

class Controller
{
boost::signals2::signal<void ()> sig;
public:
Controller() {
}

void subscribe(Listener& listener) {
// Signal with no arguments and a void return value
sig.connect(boost::bind(&Listener::OnUpdate, &listener));
}

void DoWork() const {
// Call all of the slots
sig();
}

void Update();
};

int main() {

View l1, l2;
Controller c;

c.subscribe(l1);

std::cout << "One subscribed:\n";
c.DoWork();

c.subscribe(l2);

std::cout << "\nBoth subscribed:\n";
c.DoWork();
}

打印:

One subscribed:
Updating in View

Both subscribed:
Updating in View
Updating in View

计算机,简化:现在是 C++ 风格

也许 C++ 中一个更有说服力的例子是:

Live On Coliru

#include <boost/signals2.hpp>
#include <iostream>

struct View {
void OnUpdate() { std::cout << "Updating in View\n"; }
};

class Controller {
using UpdateHandler = boost::signals2::signal<void()>;
UpdateHandler sig;

public:
Controller() {}

void subscribe(UpdateHandler::slot_type handler) { sig.connect(handler); }
void DoWork() const { sig(); }
void Update();
};

int main() {

View l1;
Controller c;
c.subscribe(std::bind(&View::OnUpdate, &l1));
c.subscribe([] { std::cout << "Or we can attach a random action\n"; });

c.DoWork();
}

哪个打印

Updating in View
Or we can attach a random action

关于c++ - 通过 boost 信号 2 的观察者模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28416088/

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