Created
May 14, 2014 14:18
-
-
Save poseidon4o/9239062fa87a099df327 to your computer and use it in GitHub Desktop.
Simple events with C++11
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 <windows.h> | |
#include <list> | |
#include <map> | |
#include <functional> | |
#include <string> | |
#include <iostream> | |
#include <algorithm> | |
using namespace std; | |
typedef function<bool()> pred_f; | |
typedef function<void()> handler_f; | |
typedef list<handler_f> handler_list; | |
class handler_cls; | |
class event_cls { | |
friend handler_cls; | |
string name; | |
pred_f & predicate; | |
handler_list handlers; | |
public: | |
event_cls(string name, pred_f predicate): name(name), predicate(predicate) {} | |
void add_handler(handler_f && handler) { | |
handlers.push_back(handler); | |
} | |
}; | |
class handler_cls { | |
typedef map<string, pair<pred_f, handler_list> > event_map; | |
private: | |
event_map events; | |
public: | |
void add_event(event_cls & event) { | |
events[event.name].first = event.predicate; | |
events[event.name].second.insert( | |
events[event.name].second.end(), | |
event.handlers.begin(), | |
event.handlers.end() | |
); | |
} | |
void check_events() { | |
for(auto & event : events) { | |
if(!event.second.first()) { | |
continue; | |
} | |
for(auto & handler : event.second.second) { | |
handler(); | |
} | |
} | |
} | |
} ev; | |
int main() { | |
event_cls arrow_up(string("up"), []() -> bool { | |
return GetAsyncKeyState(VK_UP); | |
}); | |
arrow_up.add_handler([](){ | |
cout << "up - first\n"; | |
}); | |
arrow_up.add_handler([](){ | |
cout << "up - second\n"; | |
}); | |
event_cls arrow_down(string("down"), []() -> bool { | |
return GetAsyncKeyState(VK_DOWN); | |
}); | |
arrow_down.add_handler([](){ | |
cout << "down\n"; | |
}); | |
ev.add_event(arrow_up); | |
ev.add_event(arrow_down); | |
for(;;) { | |
ev.check_events(); | |
Sleep(1000/60); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment