Skip to content

Instantly share code, notes, and snippets.

@qqii
Last active February 22, 2018 23:59
Show Gist options
  • Save qqii/f728f8a1031e8933a71d527507159d26 to your computer and use it in GitHub Desktop.
Save qqii/f728f8a1031e8933a71d527507159d26 to your computer and use it in GitHub Desktop.
"Dynamic" dispatch...
#include <unordered_map>
#include <functional>
#include <typeindex>
#include <typeinfo>
#include <memory>
class Event {
public:
virtual ~Event(){};
};
template <class EventT>
class EventHandler : std::function<void(Event*)> {
public:
EventHandler(std::function<void(EventT*)> handler) : m_handler(handler){};
void operator()(Event* event) { m_handler(static_cast<EventT*>(event)); };
~EventHandler() = default;
protected:
std::function<void(EventT*)> m_handler;
};
class HandlerMap {
public:
void handle(Event* event) {
auto iter = handlers.find(std::type_index(typeid(*event)));
if (iter != handlers.end()) {
iter->second(event);
}
};
template <class EventT>
void registerHandler(std::function<void(EventT*)> handler) {
handlers[std::type_index(typeid(EventT))] = EventHandler(handler);
}
template <class EventT>
void registerHandler(EventHandler<EventT> handler) {
handlers[std::type_index(typeid(EventT))] = handler;
}
~HandlerMap() = default;
protected:
typedef std::unordered_map<std::type_index, std::function<void(Event*)>>
Handlers;
Handlers handlers;
};
int main() {
HandlerMap map;
map.registerHandler(EventHandler<IntEvent>(foo));
map.registerHandler(EventHandler<FloatEvent>(bar));
map.handle(new IntEvent(5));
map.handle(new FloatEvent(20));
std::cout << "Press any key to quit..." << std::endl;
(void)getchar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment