#include <iostream>
#include <vector>
#include <map>
typedef int (*EventHandler)(void*);
class EventTable {
public:
void Register(int event_type, EventHandler handler) {
handlers_[event_type] = handler;
}
EventHandler Lookup(int event_type) const {
auto it = handlers_.find(event_type);
if (it != handlers_.end()) {
return it->second;
}
return nullptr;
}
private:
std::map<int, EventHandler> handlers_;
};
class EventDispatcher {
public:
EventDispatcher() : table_() {}
void Register(int event_type, EventHandler handler) {
table_.Register(event_type, handler);
}
int Dispatch(int event_type, void* event_data) {
EventHandler handler = table_.Lookup(event_type);
if (handler) {
return handler(event_data);
}
return -1;
}
private:
EventTable table_;
};
int HandleEventA(void* data) {
std::cout << "Handling Event A" << std::endl;
return 0;
}
int HandleEventB(void* data) {
std::cout << "Handling Event B" << std::endl;
return 0;
}
int main() {
EventDispatcher dispatcher;
dispatcher.Register(1, HandleEventA);
dispatcher.Register(2, HandleEventB);
std::vector<int> events = {1, 2, 3};
for (auto event : events) {
dispatcher.Dispatch(event, nullptr);
}
return 0;
}