Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@darkf
Created February 8, 2014 11:57
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save darkf/8882611 to your computer and use it in GitHub Desktop.
Save darkf/8882611 to your computer and use it in GitHub Desktop.
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