C++中的事件

Rob*_*ert 22 c++

我不确定如何在线查找...我认为它们可能在C++中被称为不同的东西

我想要一个简单的事件系统,就像

event myCustomEvent;
myCustomEvent.subscribe( void myHandler(string) );
myCustomEvent.fire("a custom argument");
// myHandler prints out the string passed in the first argument


event myNewCustomEvent;
myNewCustomEvent.subscribe( void myNewHandler(int) );
myNewCustomEvent.fire(10);
// myHandler prints 10
Run Code Online (Sandbox Code Playgroud)

我可以通过一个简单的类很容易地做到这一点 - 但是当我希望有一个事件将不同类型或数量的参数传递给我必须编写的订阅者,并定义一个全新的事件类..我认为它有成为一些库,或者甚至可能是Visual C++ 2008中的原生代码,它们将起到与此类似的作用.它基本上只是Observer模式的一个实现,所以在C++中做起来并不是太不可能

这真的让我感激它在JavaScript中有多好,不必担心你传递的参数.

告诉我这是不是一个愚蠢的问题.

Jer*_*nes 19

看一下增强信号库.结合函数绑定库,您可以完全按照您的要求进行操作.


Jim*_*uck 11

我正是为了这个目的使用sigslot.

  • 这正是我所寻找的.stackoverflow很棒. (3认同)

Kei*_*las 8

来自GOF的观察者模式几乎是你想要的.

在本书中,它有C++代码...

此外,和往常一样,Boost也有你可以使用的东西


Ecl*_*pse 6

有一个本机Visual C++ 事件系统.它主要用于COM,但它也支持本机C++.

这里:

[event_source(native)]
class CSource {
public:
   __event void MyEvent(int nValue);
};

[event_receiver(native)]
class CReceiver {
public:
   void MyHandler1(int nValue) {
      printf_s("MyHandler1 was called with value %d.\n", nValue);
   }

   void MyHandler2(int nValue) {
      printf_s("MyHandler2 was called with value %d.\n", nValue);
   }

   void hookEvent(CSource* pSource) {
      __hook(&CSource::MyEvent, pSource, &CReceiver::MyHandler1);
      __hook(&CSource::MyEvent, pSource, &CReceiver::MyHandler2);
   }

   void unhookEvent(CSource* pSource) {
      __unhook(&CSource::MyEvent, pSource, &CReceiver::MyHandler1);
      __unhook(&CSource::MyEvent, pSource, &CReceiver::MyHandler2);
   }
};

int main() {
   CSource source;
   CReceiver receiver;

   receiver.hookEvent(&source);
   __raise source.MyEvent(123);
   receiver.unhookEvent(&source);
}
Run Code Online (Sandbox Code Playgroud)