#include #include namespace CXXHelper { template class Event { protected: std::list > m_handlers; public: Event () { } Event (Event && from) { m_handlers.swap (from.m_handlers); } Event (const Event & from) { from.CopyTo (*this); } Event & operator = (const Event & from) { from.CopyTo (*this); return (*this); } Event & operator = (Event && from) { m_handlers.swap (from.m_handlers); return (*this); } void swap (Event & from) { m_handlers.swap (from.m_handlers); } void CopyTo (Event & to) const { to.m_handlers = m_handlers; } void Release () { m_handlers.clear (); } virtual ~Event () { } public: inline void operator () (Args... arg) { Invoke (arg...); } inline void Invoke (Args... arg) { for (auto & h : m_handlers) h (arg...); } public: inline void RemoveAll () { Release (); } inline bool IsEmpty () const { return m_handlers.empty (); } inline int GetSize () const { return (int)m_handlers.size (); } inline void AppendFrom (const Event & from) { for (auto h : from.m_handlers) this->m_handlers.push_back (h); } public: Event & operator += (Event & from) { AppendFrom (from); return (*this); } public: template Event & operator += (TA v) { Push (v); return (*this); } public: // lambda 表达式会到这里 // Binder (bind 结果) 会到这里 template // inline void Push (const TX & handler) inline void Push (TX handler) { m_handlers.push_back (std::move (handler)); } // 静态函数会到这里 inline void Push (void (*fn) (Args...)) { m_handlers.push_back (std::move (fn)); } // 类的成员函数会到这里 - 3 个 // 这里用了个小技巧: 把类实例和成员函数转换成一个临时的 lambda 函数 template inline void Push (TC * inst, void (TC::* mfn) (Args...)) { m_handlers.push_back ([inst, mfn] (Args... args) {(*inst.*mfn) (args...); }); } template void Push (TC * inst, void (TC::* mfn) (Args...) const) { m_handlers.push_back ([inst, mfn] (Args... args) {(*inst.*mfn) (args...); }); } template void Push (const TC * inst, void (TC::* mfn) (Args...) const) { m_handlers.push_back ([inst, mfn] (Args... args) {(*inst.*mfn) (args...); }); } }; }