Created
April 3, 2018 19:39
-
-
Save Gydo194/80c9c43dd769f88c956c940a1affe24b to your computer and use it in GitHub Desktop.
C++ templated event handler (callback)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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