I’m trying to create an event system with notifications via callbacks. I have the code written, but it is dependent on void pointers to work. After how hard void pointers bit me in my last project I would like to replace the void pointers with something that compile time type checks.
Here’s the Event class
enum EventType {
TEST_TYPE_A,
TEST_TYPE_B
};
// used by event receivers
class EventHandler
{
public:
virtual void handleEvent(EventType type, void* data) = 0; // PROBLEM HERE
};
// class to send events to objects registered for them
class Event
{
private:
std::multimap<EventType, EventHandler*> eventMap;
public:
void registerForEvent(EventType type, EventHandler *handler) {
eventMap.insert(std::pair<EventType, EventHandler*>(type, handler));
}
void sendEvent(EventType type, void* data) { // PROBLEM HERE
std::multimap<EventType, EventHandler*>::iterator it;
std::pair<std::multimap<EventType, EventHandler*>::iterator, std::multimap<EventType, EventHandler*>::iterator> matches;
matches = eventMap.equal_range(type);
for (it = matches.first; it != matches.second; ++it) {
it->second->handleEvent(type, data);
}
}
};
And here’s the code to test the Event class
class Handler : public EventHandler {
public:
void handleEvent(EventType type, void* data) {
char *cp = (char*)data;
printf("Handler: %s \n", cp);
}
};
int main(int argc, const char* argv[]) {
Handler handle;
Event event;
char c[] = "what?";
event.registerForEvent(TEST_TYPE_A, &handle);
event.sendEvent(TEST_TYPE_A, (void*)c);
return 0;
}
Thanks in advance for any pointers! I’m kinda stuck on this.
Let’s apply templates: