Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple event system in C++
#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
You can’t perform that action at this time.