使用C++模拟C#的委托机制
2012-06-01 19:24:17 来源:WEB开发网核心提示://Event.h #ifndef _EVENT_H_#define _EVENT_H_class EmptyObject {};template<typename F>class Event{public: Event() :m_pObjectPtr(NULL), m_pMemeberFunction
//Event.h #ifndef _EVENT_H_ #define _EVENT_H_ class EmptyObject {}; template<typename F> class Event { public: Event() :m_pObjectPtr(NULL), m_pMemeberFunctionPtr(NULL) { } virtual ~Event() { if (m_pMemeberFunctionPtr != NULL) { delete m_pMemeberFunctionPtr; m_pMemeberFunctionPtr = NULL; } } template<typename C,typename M> Event(C* pObjectPtr,const M& MemeberFunctionPtr) : m_pObjectPtr((EmptyObject*)pObjectPtr) { M* pMFPtr = new M; *pMFPtr = MemeberFunctionPtr; m_pMemeberFunctionPtr = (F*)pMFPtr; } Event<F>& operator += (const Event<F>& event) { if (event.GetObjectPtr() == this->GetObjectPtr() && *event.GetMemeberFunctionPtr() == *this->GetMemeberFunctionPtr()) { return *this; } this->m_pObjectPtr = event.GetObjectPtr(); if (m_pMemeberFunctionPtr != NULL) { delete m_pMemeberFunctionPtr; m_pMemeberFunctionPtr = NULL; } this->m_pMemeberFunctionPtr = new F; *this->m_pMemeberFunctionPtr = *event.GetMemeberFunctionPtr(); return *this; } Event<F>& operator -= (const Event<F>& event) { if (event.GetObjectPtr() == this->GetObjectPtr() && *event.GetMemeberFunctionPtr() == *this->GetMemeberFunctionPtr()) { this->m_pObjectPtr = NULL; if (m_pMemeberFunctionPtr != NULL) { delete m_pMemeberFunctionPtr; m_pMemeberFunctionPtr = NULL; } } return *this; } EmptyObject* GetObjectPtr() const { return this->m_pObjectPtr; } F* GetMemeberFunctionPtr() const { return this->m_pMemeberFunctionPtr; } private: EmptyObject* m_pObjectPtr; F* m_pMemeberFunctionPtr; }; typedef EmptyObject Delegater; #define InvokeEvent(EventHandler) \ if (EventHandler != NULL) \ if (EventHandler->GetObjectPtr() != NULL && *EventHandler->GetMemeberFunctionPtr() != NULL) \ ((EventHandler->GetObjectPtr())->*(*EventHandler->GetMemeberFunctionPtr())) #endif /*_EVENT_H_*/
//测试代码: #include "Event.h" typedef void (Delegater::*ClickEvent)(int); class CForm { public: void FormClick() { InvokeEvent((&OnClick))(10); } Event<ClickEvent> OnClick; }; class CWindows { public: CWindows() { Form.OnClick += Event<ClickEvent>(this,&CWindows::OnClick); } void Run() { Form.FormClick(); } void RemoveEvent() { Form.OnClick -= Event<ClickEvent>(this,&CWindows::OnClick); } void OnClick(int n) { printf("%d\r\n",n); } private: CForm Form; }; int _tmain(int argc, _TCHAR* argv[]) { CWindows Windows; Windows.Run(); Windows.RemoveEvent(); Windows.Run(); return 0; }
更多精彩
赞助商链接