Skip to content

Instantly share code, notes, and snippets.

@Leowbattle
Last active April 14, 2018 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Leowbattle/a6fc942985e33020b9cc383ee1faa76b to your computer and use it in GitHub Desktop.
Save Leowbattle/a6fc942985e33020b9cc383ee1faa76b to your computer and use it in GitHub Desktop.
EventsV2
#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 */
#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