简单的C++委托 —— 用模板类实现类成员函数的回调

简单的C++委托 —— 用模板类实现类成员函数的回调

template <class R, class P1, class P2>
class IDelegate
{
public:
 virtual R Invoke(P1, P2) = 0;
};


template <class T, class R, class P1, class P2>
class CDelegate : public IDelegate<R, P1, P2>
{
protected:

 typedef R (T::*pfnHandle)(P1, P2);

 const pfnHandle m_pfn;

 T* const m_pThis;

public:

 CDelegate(T* const pThis, const pfnHandle pfn)
 :m_pThis(pThis), m_pfn(pfn)
 {
  if (m_pThis == NULL || m_pfn == NULL)
  {
   throw;
  } 
 }

 virtual R Invoke(P1 p1, P2 p2)
 {
  return (m_pThis->*m_pfn)(p1, p2);
 }

};

class CDelegateSource
{
public:
 CDelegateSource()
 : m_lpCallBack(NULL)
 {
 }

 void SetCallBack(IDelegate<bool, int, int>* newVal)
 {
  m_lpCallBack = newVal;
 }

 void DoSomething()
 {
  for (int i = 0; i < 10; i++)
  {   
   if (m_lpCallBack != NULL)
   {
    m_lpCallBack->Invoke(i, i * i);
   }
  }
 }

private:

 IDelegate<bool, int, int>* m_lpCallBack;

};

class CDelegateTester
{
private:

 bool OnCallBack(int nParam1, int nParam2)
 {
  printf("OnCallBack -> nParam1:%d, nParam2:%d\r\n", nParam1, nParam2);

  return true;
 }

 CDelegate<CDelegateTester, bool, int, int> m_OnCallBack;

public:

 CDelegateTester()
 : m_OnCallBack(this, OnCallBack)
 {
 }

 void Execute()
 {
  CDelegateSource src;
  src.SetCallBack(&m_OnCallBack);
  src.DoSomething();
 }
};

void main()
{
 CDelegateTester Tester;
 Tester.Execute();

 getchar();
}

你可能感兴趣的:(简单的C++委托 —— 用模板类实现类成员函数的回调)