forked from MCGallaspy/events
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.cpp
74 lines (61 loc) · 2.28 KB
/
example.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* An example that shows how these classes may be used.
* 1. Declare your events. They must be derived from BaseEvent.
* 2. Declare your event listeners. They must be derived from
* EventListener<...> with one type parameter for each event
* class they may handle.
* 3. Declare appropriate overloaded onEvent methods.
* Failure to include one makes the class abstract.
* 4. Register your event listeners to the event dispatcher
* for each kind of event they handle:
* EventDispatcher::getInstance().addListener<EventType>(listener)
* 5. Post events through the event dispatcher to trigger
* the handler functions:
* EventDispatcher::getInstance().post(event);
*/
#include <iostream>
#include "events.h"
using namespace std;
class AEvent : public BaseEvent {};
class BEvent : public BaseEvent {};
class DEvent : public AEvent {}; // Events can be arbitrarily derived.
class Foo : public EventListener<AEvent, DEvent, BEvent> {
public:
void onEvent(const AEvent& evt) {
cout << "Foo is handling AEvent" << endl;
}
void onEvent(const BEvent& evt) {
cout << "Foo is handling BEvent" << endl;
}
// Failing to create a concrete onEvent will result in an abstract base class
void onEvent(const DEvent& evt) {
cout << "Foo is handling DEvent" << endl;
}
};
class Bar : public EventListener<AEvent> {
public:
void onEvent(const AEvent& evt) {
cout << "Bar is handling AEvent" << endl;
}
};
int main() {
Foo *foo = new Foo;
auto ed = EventDispatcher::getInstance();
ed.addListener<AEvent>(foo);
ed.addListener<BEvent>(foo);
ed.addListener<DEvent>(foo);
Bar *bar = new Bar;
ed.addListener<AEvent>(bar);
// A compile time error. You can't accidentally listen to unhandled events.
// ed.addListener<BEvent>(bar);
// A derived event can be handled by a listener for the base event.
ed.connectHandler<DEvent, AEvent>(bar);
// ed.connectHandler<AEvent, AEvent>(bar); // An error.
// ed.connectHandler<DEvent, BEvent>(bar); // An error -- DEvent is not derived from BEvent.
cout << "Posting AEvent..." << endl;
ed.post(AEvent());
cout << "Posting BEvent..." << endl;
ed.post(BEvent());
cout << "Posting DEvent..." << endl;
ed.post(DEvent());
return 0;
}