Last active
April 14, 2018 09:05
-
-
Save Leowbattle/a6fc942985e33020b9cc383ee1faa76b to your computer and use it in GitHub Desktop.
EventsV2
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
#ifndef Event_hpp | |
#define Event_hpp | |
#include <vector> | |
#include <functional> | |
class Event; | |
typedef std::function<void(Event*)> EventHandler; | |
class Event { | |
public: | |
virtual void operator()() final { | |
for (auto handler: getHandlers()) { | |
handler(this); | |
} | |
execute(); | |
} | |
private: | |
virtual void execute() = 0; | |
virtual std::vector<EventHandler> getHandlers() = 0; | |
}; | |
#define HANDLER_METHODS \ | |
public:\ | |
static void addHandler(EventHandler eh) {\ | |
handlers.emplace_back(eh);\ | |
}\ | |
private:\ | |
virtual std::vector<EventHandler> getHandlers() {\ | |
return handlers;\ | |
}\ | |
static std::vector<EventHandler> handlers; | |
#define HANDLERS_INIT(__TYPENAME__) \ | |
std::vector<EventHandler> __TYPENAME__::handlers; | |
#endif /* Event_hpp */ |
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 <iostream> | |
#include "Event.hpp" | |
class EventTest: public Event { | |
HANDLER_METHODS | |
private: | |
virtual void execute() { | |
std::cout << "I am an event" << std::endl; | |
} | |
}; | |
HANDLERS_INIT(EventTest) | |
class EventTest2: public Event { | |
HANDLER_METHODS | |
private: | |
virtual void execute() { | |
std::cout << "I am also an event" << std::endl; | |
} | |
}; | |
HANDLERS_INIT(EventTest2) | |
int main(int argc, const char * argv[]) { | |
EventTest::addHandler([](Event* e) { | |
std::cout << "I am a handler" << std::endl; | |
}); | |
EventTest2::addHandler([](Event* e) { | |
std::cout << "I am also a handler" << std::endl; | |
}); | |
EventTest et; | |
et(); | |
EventTest2 et2; | |
et2(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment