#pragma once #include #include #include #include #include #include #if __cplusplus <= 199711L // #error This file needs at least a C++11 compliant compiler, try using: // #error $ g++ -std=c++11 .. #endif using namespace std; struct ts { uint16_t x; uint16_t y; uint32_t time; }; #define TEMPLATE template // Abstract Class for EventHandler to notify of a change class EventHandlerBase { public: virtual void execute() = 0; }; // Event Handler Class : Handles Callback template class EventHandler : public EventHandlerBase { // Defining type for function pointer typedef void (Class::* _fptr)(struct ts); private: struct ts ts_sample = { 0, 0, 500 }; public: // Object of the Listener Class* object; // Function for callback _fptr function; EventHandler(Class* obj, _fptr func) { object = obj; function = func; } void execute() { (object->*function)(); } }; // Class to create a event class Event { // To store all listeners of the event typedef std::map EventHandlerMap; EventHandlerMap handlers; int count; public: template void addListener(Class* obj, void (Class::* func)(void)) { handlers[count] = new EventHandler(obj, func); count++; } void execute() { for (EventHandlerMap::iterator it = handlers.begin(); it != handlers.end(); ++it) { it->second->execute(); } } }; class EventManager { struct EventType { Event* event; string name; }; std::vector _events; static EventManager* _Instance; // Constructor EventManager() {}; public: static EventManager* Instance() { if (!_Instance) { _Instance = new EventManager(); } return _Instance; } // static EventManager* Instance() void createEvent(string name) { for (vector::iterator it = _events.begin(); it != _events.end(); ++it) { EventType e = *it; if (e.name.compare(name) == 0) return; } EventType e; e.event = new Event(); e.name = name; _events.push_back(e); } // createEvent template bool subscribe(string name, Class* obj, void (Class::* func)(void)) { for (vector::iterator it = _events.begin(); it != _events.end(); ++it) { EventType e = *it; if (e.name.compare(name) == 0) { e.event->addListener(obj, func); return true; } } return false; } void execute(string name) { for (vector::iterator it = _events.begin(); it != _events.end(); ++it) { EventType e = *it; if (e.name.compare(name) == 0) { e.event->execute(); } } } };