用C++实现事件

use*_*867 4 c++ events

在对Internet进行一些研究以获得在C++中实现事件的有效方法之后,我发现了以下方法

  • 接口类 - 应用程序可以覆盖派生类中的虚函数
  • 使用函数指针的正常回调机制
  • 代表使用Boost.function
  • 信号和插槽(在Qt中使用)

我对这些中的每一个的优点和缺点以及何时使用其中的任何一个感到困惑.哪种方法最好,为什么?还有其他解决方案比列出的解决方案更好吗?

seh*_*ehe 8

FWIW,我的投票将是任何一天的Boost Signals.

Boost确保可移植性.当然它与Boost Asio,Functional,Bind等很好地集成.

更新:

Signals2

本文档描述了原始Boost.Signals库的线程安全变体.对支持线程安全的接口进行了一些更改,主要是关于自动连接管理.[....]

Boost确保可移植性.当然它与Boost Asio,Functional,Bind等很好地集成.

boost :: signals2 :: signal sig;

sig.connect(&print_sum);
sig.connect(&print_product);
sig.connect(&print_difference);
sig.connect(&print_quotient);

sig(5., 3.);
Run Code Online (Sandbox Code Playgroud)

该程序将打印出以下内容:

The sum is 8
The product is 15
The difference is 2
The quotient is 1.66667
Run Code Online (Sandbox Code Playgroud)

样本行动:

void print_sum(float x, float y)
{
  std::cout << "The sum is " << x+y << std::endl;
}

void print_product(float x, float y)
{
  std::cout << "The product is " << x*y << std::endl;
}

void print_difference(float x, float y)
{
  std::cout << "The difference is " << x-y << std::endl;
}

void print_quotient(float x, float y)
{
  std::cout << "The quotient is " << x/y << std::endl;
}
Run Code Online (Sandbox Code Playgroud)