Skip to content

Instantly share code, notes, and snippets.

@hadashiA
Created February 16, 2013 11:08
Show Gist options
  • Save hadashiA/4966452 to your computer and use it in GitHub Desktop.
Save hadashiA/4966452 to your computer and use it in GitHub Desktop.
std::function を使ったイベントハンドラ
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <string>
typedef int EventType;
struct Event {
public:
Event(EventType t) : type(t) {}
EventType type;
};
class A {
public:
void Callback(const Event& e) {
std::cout << "A::Callback(" << e.type << ")" << std::endl;
}
};
class B {
public:
void Callback(const Event& e) {
std::cout << "B::Callback(" << e.type << ")" << std::endl;
}
};
class EventDispatcher {
public:
typedef std::function<void (const Event&)> EventCallback;
typedef std::multimap<EventType, EventCallback> EventCallbackTable;
template <typename T>
bool On(EventType type, T& listener) {
EventCallback callback = std::bind(&T::Callback, listener,
std::placeholders::_1);
std::pair<EventType, EventCallback> pair(type, callback);
callbacks_.insert(pair);
return true;
}
void Emit(const Event& event) {
std::pair<EventCallbackTable::iterator, EventCallbackTable::iterator> range = callbacks_.equal_range(event.type);
for (EventCallbackTable::iterator i = range.first; i != range.second; i++) {
EventType type = i->first;
EventCallback callback = i->second;
callback(event);
}
}
private:
EventCallbackTable callbacks_;
};
int main (int argc, char** argv) {
EventDispatcher dispatcher;
Event event1(1);
Event event2(2);
A *a = new A;
B *b = new B;
dispatcher.On(1, *a);
dispatcher.On(1, *b);
dispatcher.On(2, *a);
delete a;
delete b;
dispatcher.Emit(event1);
// A::Callback(1)
// B::Callback(1)
dispatcher.Emit(event2);
// A::Callback(2)
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment