C++实现委托与事件代理_zx504287的专栏-CSDN博客_c++委托和事件
注意reinterpret_cast强制类型的转换的理解
#include<iostream>
#include<vector>
#include<stdio.h>
using namespace std;
class EmptyClass{};
/**
* reinterpret_cast转化一个指针为其他类型的指针,这个操作符能够在非相关的类型之间转换,
* 操作结果只是简单的从一个指针到别的指针的二进制拷贝。reinterpret_cast转换成其它类型的目的只是临时的隐藏自己的信息。
*/
template<class RetCond=bool, class RetEvent=void>
class Listener{
private:
typedef RetCond (EmptyClass::*pCondFunc)();
typedef RetEvent (EmptyClass::*pEventFunc)();
EmptyClass* m_pCThis;
pCondFunc m_pFCond;
struct EventFunc{
EmptyClass* m_pEThis;
pEventFunc m_pFEvent;
};
vector<EventFunc> m_event;
public:
template<class TypeCond>
void SetListener(TypeCond& pCThis, RetCond(TypeCond::*pFuncCond)()){
m_pCThis = reinterpret_cast<EmptyClass*>(&pCThis); // Keyboard对象
m_pFCond = reinterpret_cast<pCondFunc>(pFuncCond); // KeyDown函数,无参
}
/**
* 添加事件函数
*/
template<class TypeEvent>
void AddEventFunc(TypeEvent& pEThis, RetEvent(TypeEvent::*pFuncEvent)()){
EventFunc ef;
ef.m_pEThis = reinterpret_cast<EmptyClass*>(&pEThis);
ef.m_pFEvent = reinterpret_cast<pEventFunc>(pFuncEvent);
m_event.push_back(ef);
}
/**
* 重载()操作符
*/
void operator()() const{
if((m_pCThis->*m_pFCond)()){
unsigned int index = 0;
while(index < m_event.size()){
(m_event[index].m_pEThis->*m_event[index].m_pFEvent)();
++index;
}
}
}
};
class Keyboard{
public:
bool KeyDown(){
if(getchar() == 'k'){
return true;
}
}
};
class Role{
public:
void TriggerSkill(){cout<<"Trigger SkillYes!"<<endl;}
void SkillExpUp(){cout<<"Skill Exp UpYes!"<<endl;}
void AttackPowerUP(){cout<<"Attack Power UpYes!"<<endl;}
void IsHitMonster(){cout<<"Hit The MonsterYes!"<<endl;}
};
int main(){
Keyboard k;
Role r;
Listener<bool, void> listen;
listen.SetListener(k, &Keyboard::KeyDown);
listen.AddEventFunc(r,&Role::TriggerSkill);
listen.AddEventFunc(r, &Role::AttackPowerUP);
listen.AddEventFunc(r, &Role::SkillExpUp);
listen.AddEventFunc(r, &Role::IsHitMonster);
cout << "Now, I want to handle events here ! \n" << endl;
listen();
return 0;
}