123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148 |
- #pragma once
- #include <list>
- #include <functional>
- namespace CXXHelper
- {
- template <typename... Args>
- class Event
- {
- protected:
- std::list <std::function <void (Args...)> > 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 <typename TA>
- Event & operator += (TA v)
- {
- Push (v);
- return (*this);
- }
- public:
- // lambda 表达式会到这里
- // Binder (bind 结果) 会到这里
- template <typename TX>
- // 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 <typename TC>
- inline void Push (TC * inst, void (TC::* mfn) (Args...))
- {
- m_handlers.push_back ([inst, mfn] (Args... args) {(*inst.*mfn) (args...); });
- }
- template <typename TC>
- void Push (TC * inst, void (TC::* mfn) (Args...) const)
- {
- m_handlers.push_back ([inst, mfn] (Args... args) {(*inst.*mfn) (args...); });
- }
- template<typename TC>
- void Push (const TC * inst, void (TC::* mfn) (Args...) const)
- {
- m_handlers.push_back ([inst, mfn] (Args... args) {(*inst.*mfn) (args...); });
- }
- };
- }
|