C++ 事件委托实现

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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值