首页 > 代码库 > 使用C++模拟C#的委托机制

使用C++模拟C#的委托机制

1. [代码][C/C++]代码     

//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
 {http://www.huiyi8.com/hunsha/chuangyi/?
  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_*/
2. [代码][C/C++]代码     

//测试代码:
#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;
}

使用C++模拟C#的委托机制