#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
template<typename tParam>
class SlotBase
{
public:
virtual void Exec(tParam param) = 0;
};
template<class T, class tParam>
class SlotImpl : public SlotBase<tParam>
{
public:
SlotImpl(T* pObj, void (T::*func)(tParam) )
{
m_pObj = pObj;
m_Func = func;
}
void Exec( tParam param)
{
(m_pObj->*m_Func)(param);
}
private:
T* m_pObj;
void (T::*m_Func)(tParam);
};
template<class tParam>
class Slot
{
public:
template<class T>
Slot(T* pObj, void (T::*func)(tParam))
{
m_pSlotBase = new SlotImpl<T,tParam>(pObj, func);
}
~Slot()
{
delete m_pSlotBase;
}
void Exec(tParam param1)
{
m_pSlotBase->Exec(param1);
}
private:
SlotBase<tParam>* m_pSlotBase;
};
template<typename tParam>
class Signal
{
public:
template<class T>
void Bind(T* pObj, void (T::*func)(tParam))
{
m_pSlotSet.push_back( new Slot<tParam>(pObj,func) );
}
~Signal()
{
for(int i=0;i<(int)m_pSlotSet.size();i++)
{
delete m_pSlotSet[i];
}
}
void operator()(tParam param1)
{
for(int i=0;i<(int)m_pSlotSet.size();i++)
{
m_pSlotSet[i]->Exec(param1);
}
}
private:
vector< Slot<tParam>* > m_pSlotSet;
};
#define Connect( sender, signal, receiver, method) ( (sender)->signal.Bind(receiver, method) )
class A
{
public:
void FuncOfA(int param)
{
printf("A::FuncOfA(%d)\n", param);
}
};
class B
{
public:
void FuncOfB(int param)
{
printf("B::FuncOfB(%d)\n", param);
}
};
class C
{
public:
void SetValue(int value)
{
ValueChanged(value);
}
public:
Signal<int> ValueChanged;
};
int main()
{
A* pA = new A;
B* pB = new B;
C* pC = new C;
Connect(pC, ValueChanged, pA, &A::FuncOfA);
//Connect(pC, ValueChanged, pB, &B::FuncOfB);
//pC->ValueChanged(10);
pC->SetValue(10);
//pC->SetValue(5);
//pC->SetValue(5);
delete pC;
delete pB;
delete pA;
system("pause");
return 0;
}
转自:http://www.cnitblog.com/luckydmz/archive/2010/11/15/71336.html