I\'m not sure how to look for this online... I think they might be called something different in C++
I want to have a simple event system, somthing like
Take a look at the boost signal library. Combined with the function and bind libraries, you can do exactly what you are looking for.
I use sigslot for exactly this purpose.
The observer pattern from the GOF is pretty much what you want.
In the book, it has C++ code for this...
Also, as always, Boost has stuff you can make use of as well
There is a native Visual C++ event system. It's mostly for COM, but it has native C++ support too.
From here:
[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);
}
I use libsigc++. It's native for gtkmm.
A simple example losely adapted from the tutorial:
#include <iostream>
#include <sigc++/sigc++.h>
using namespace std;
class AlienDetector {
public:
void run ();
sigc::signal<void> signal_detected;
};
void warn_people () {
cout << "There are aliens in the carpark!" << endl;
}
void AlienDetector::run () {
signal_detected.emit ();
}
int main () {
AlienDetector mydetector;
mydetector.signal_detected.connect (sigc::ptr_fun (warn_people));
mydetector.run ();
}
It also provides a mechanism to connect member-functions of specific objects to signals using sigc::mem_fun instead of sigc::ptr_fun:
sigc::mem_fun (someobject, &SomeClass::some_method);
This pretty much provides anything that is possible with GLib-signals.