CEGUI对回调函数的封装

#include <iostream>
using namespace std;
// 回调函数 虚基类
class SlotFunctorBase 
{
public:
	virtual ~SlotFunctorBase() {};
	virtual bool operator()(bool flag) = 0;
};

// 普通函数的封装类
class FreeFunctionSlot : public SlotFunctorBase
{
public:
	// 回调函数 的 签名(Signature)
	// CEGUI 的 回调原本是以下形式    
	// typedef bool (SlotFunction)(const EventArgs&);
	typedef bool (SlotFunction)(bool flag);

	FreeFunctionSlot(SlotFunction* func) :
	d_function(func)
	{}

	virtual bool operator()(bool flag)
	{
		return d_function(flag);
	}

private:
	SlotFunction* d_function;
};

// 类成员函数作为回调函数的封装类;
template<typename T>
class MemberFunctionSlot : public SlotFunctorBase
{
public:
    // 回调函数 的 签名(Signature)
    // CEGUI 的 回调原本是以下形式,化简为bool flag
    // typedef bool (SlotFunction)(const EventArgs&);
    typedef bool(T::*MemberFunctionType)(bool flag);
    
    MemberFunctionSlot(MemberFunctionType func, T* obj) :
        d_function(func),
        d_object(obj)
    {}

    virtual bool operator()(bool flag)
    {
        return (d_object->*d_function)(flag);
    }
private:
    MemberFunctionType d_function;
    T* d_object;
};


class SubscriberSlot  // 回调函数封装类
{  
public:  
	bool operator()(bool flag) const
	{
		return (*d_functor_impl)(flag);
	}	

	// 普通回调函数的构造方法
    SubscriberSlot(FreeFunctionSlot::SlotFunction* func):
		d_functor_impl(new FreeFunctionSlot(func))
    {}
    
	// 类成员函数作为回调函数的构造方法
	template<typename T>
	SubscriberSlot(bool (T::*function)(bool flag), T* obj) :
		d_functor_impl(new MemberFunctionSlot<T>(function, obj))
	{}
	
private:
	SlotFunctorBase* d_functor_impl;
};


class TestClass
{
public:
	void callFunction()
	{
		SubscriberSlot afunction(&TestClass::memberFunctionToCall,this);
		afunction(m_flag);
	}	

	bool memberFunctionToCall(bool flag)
	{
		cout<< "memberFunctionToCall:\t"<<( flag ? "haha!" : "oh no !" )<<endl;
		return flag;		
	}
	
	bool m_flag;
};


bool freeFunctionToCall(bool flag)
{
	cout<< "freeFunctionToCall:\t"<<( flag ? "haha!" : "oh no !" )<<endl;
	return flag;		
}

// 调用  
int main()  
{  
	TestClass obj;
	obj.callFunction();
	
	SubscriberSlot freeFunction(&freeFunctionToCall);
	freeFunction(false);
	
	
	return 0;  
} 

                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值