-
-
Save roachsinai/c81e06cac67e3b77bd695c597c0787b2 to your computer and use it in GitHub Desktop.
Simple event system in C++
This file contains 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
#include <functional> | |
#include <map> | |
#include <typeinfo> | |
#include <iostream> | |
struct Event { | |
virtual ~Event() {} | |
}; | |
struct TestEvent : Event { | |
std::string msg; | |
TestEvent(std::string msg) : msg(msg) {} | |
}; | |
// Has the limitation that on<T> will not catch subtypes of T, only T. | |
// That may or may not be a problem for your usecase. | |
// | |
// It also doesn't (yet) let you use the subtype as an argument. | |
typedef std::multimap<const std::type_info*, | |
const std::function<void(const Event&)>> EventMap; | |
class event { | |
private: | |
static EventMap eventMap; | |
public: | |
template<typename EventWanted> | |
static void on(const std::function<void(const Event&)>& fn) { | |
event::eventMap.emplace(&typeid(EventWanted), fn); | |
} | |
static void emit(const Event& event) { | |
auto range = eventMap.equal_range(&typeid(event)); | |
for(auto it = range.first; it != range.second; ++it) | |
it->second(event); | |
} | |
}; | |
EventMap event::eventMap; | |
int main() { | |
// bind some event handlers | |
event::on<TestEvent>([](const Event& e) { std::cout << "hi from " << static_cast<const TestEvent&>(e).msg << std::endl; }); | |
event::on<TestEvent>([](const Event& e) { std::cout << "hi two" << std::endl; }); | |
// fire some events | |
event::emit(TestEvent("pinkie")); | |
event::emit(TestEvent("the brain")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment