I want to implement a callback handler. Methods should be registered as easy as the following...
std::multimap<Event::Type, std::function<void()>> actions;
void EventManager::registerAction(Event::Type event, std::function<void()> action) {
actions.insert(std::make_pair(event, action));
}
...which indeed works as intended.
But the problem with that approach is, that it is impossible to deregister a callback...
void EventManager::deregisterAction(Event::Type event, std::function<void()> action) {
for(auto i = actions.lower_bound(event); i != actions.upper_bound(event); ++i) {
// if action == i->second
}
}
...because it's impossible to compare bound functions.
Lazy deregistering also won't work because the function object can't be validated.
void EventManager::handle(Event::Type event) {
for(auto i = actions.lower_bound(event); i != actions.upper_bound(event); ++i) {
if(i->second) // returns true even if the object doesn't exist anymore
i->second();
}
}
So how should I approach an implementation like this, how can the issues I encountered be avoided?