Skip to content

Instantly share code, notes, and snippets.

@Gydo194
Created April 3, 2018 19:39
Show Gist options
  • Save Gydo194/80c9c43dd769f88c956c940a1affe24b to your computer and use it in GitHub Desktop.
Save Gydo194/80c9c43dd769f88c956c940a1affe24b to your computer and use it in GitHub Desktop.
C++ templated event handler (callback)
#ifndef EVENTHANDLER_H
#define EVENTHANDLER_H
#include <map>
using namespace std;
template<class K, class E> //KeyType, EventType
class EventHandler
{
public:
struct target { //event target (function target)
void (*callback)(E);
};
void attachEventListener(K key, target ev) {
events.insert((pair<K,target>(key,ev)));
}
void detachEventListener(K key) {
events.erase(key);
}
void pushEvent(K key, E argument) {
try {
events.at(key).callback(argument);
} catch(out_of_range oor) {
//404: event not found.
return;
}
}
private:
map<K,target> events;
};
#endif //EVENTHANDLER_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment