// // An event/listener system. // #ifndef EVENT_H #define EVENT_H #include #include class Event; class CallbackHandle { public: CallbackHandle(Event *evt, int id) : m_evt(evt), m_id(id) { } ~CallbackHandle(); private: Event *m_evt; int m_id; }; class Event { public: using Callback = std::function; CallbackHandle addListener(Callback cb) { int id = m_nextId++; m_callbacks[id] = std::move(cb); return CallbackHandle(this, id); } void remove(int id) { m_callbacks.erase(id); } void fire() { for (auto &kv : m_callbacks) kv.second(); } private: friend class CallbackHandle; std::unordered_map m_callbacks; int m_nextId = 0; }; CallbackHandle::~CallbackHandle() { if (m_evt) m_evt->remove(m_id); } #endif // EVENT_H