gpt4 book ai didi

c++ - 使用 Boost::Signals 进行 C++ 事件的完整示例

转载 作者:IT老高 更新时间:2023-10-28 13:23:36 24 4
gpt4 key购买 nike

我知道 boost.org 上的教程解决了这个问题: Boost.org Signals Tutorial ,但示例并不完整,而且有些过于简化。那里的示例没有显示包含文件,并且代码的某些部分有点模糊。

这是我需要的:
ClassA 引发多个事件/信号
ClassB 订阅这些事件(可以订阅多个类)

在我的项目中,我有一个较低级别的消息处理程序类,该类将事件引发到业务类,该业务类对这些消息进行一些处理并通知 UI (wxFrames)。我需要知道这些都是如何连接起来的(什么顺序,谁调用谁,等等)。

最佳答案

下面的代码是您所要求的最小工作示例。 ClassA 发出两个信号; SigA 不发送(并接受)任何参数,SigB 发送一个 intClassB 有两个函数,在调用每个函数时都会输出到 cout。在示例中,有一个 ClassA 实例 (a) 和两个 ClassB 实例(b b2)。 main 用于连接和触发信号。值得注意的是,ClassAClassB 彼此一无所知(即它们不受编译时限制)。

#include <boost/signal.hpp>
#include <boost/bind.hpp>
#include <iostream>

using namespace boost;
using namespace std;

struct ClassA
{
signal<void ()> SigA;
signal<void (int)> SigB;
};

struct ClassB
{
void PrintFoo() { cout << "Foo" << endl; }
void PrintInt(int i) { cout << "Bar: " << i << endl; }
};

int main()
{
ClassA a;
ClassB b, b2;

a.SigA.connect(bind(&ClassB::PrintFoo, &b));
a.SigB.connect(bind(&ClassB::PrintInt, &b, _1));
a.SigB.connect(bind(&ClassB::PrintInt, &b2, _1));

a.SigA();
a.SigB(4);
}

输出:

FooBar: 4Bar: 4

For brevity I've taken some shortcuts that you wouldn't normally use in production code (in particular access control is lax and you'd normally 'hide' your signal registration behind a function like in KeithB's example).

It seems that most of the difficulty in boost::signal is in getting used to using boost::bind. It is a bit mind-bending at first! For a trickier example you could also use bind to hook up ClassA::SigA with ClassB::PrintInt even though SigA does not emit an int:

a.SigA.connect(bind(&ClassB::PrintInt, &b, 10));

希望有帮助!

关于c++ - 使用 Boost::Signals 进行 C++ 事件的完整示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/768351/

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