C++实现的委托机制(1)(二)

2014-11-24 12:43:46 · 作者: · 浏览: 1
false;
CStaticDelegate * cast = static_cast(_delegate);
return cast->mFunc == mFunc;
}
private:
Func mFunc;
};

可以看到,CStaticDelegate只是简单地封装了普通函数指针,代码也非常简单

(类的某些成员函数,如isType和compare使用了RTTI,

C++的动态类型判断不熟的可以猛击这里http://blog.csdn.net/gouki04/article/details/6796173

好了,注意了,下面开始封装类成员函数指针

copy to clipboardprint template
class CMethodDelegate : public IDelegate
{
public:
typedef void (T::*Method)();
CMethodDelegate(T * _object, Method _method) : mObject(_object), mMethod(_method) { }
virtual bool isType( const std::type_info& _type) { return typeid(CMethodDelegate) == _type; }
virtual void invoke()
{
(mObject->*mMethod)();
}
virtual bool compare(IDelegate *_delegate) const
{
if (0 == _delegate || !_delegate->isType(typeid(CMethodDelegate)) ) return false;
CMethodDelegate* cast = static_cast(_delegate);
return cast->mObject == mObject && cast->mMethod == mMethod;
}
private:
T * mObject;
Method mMethod;
};
template
class CMethodDelegate : public IDelegate
{
public:
typedef void (T::*Method)();
CMethodDelegate(T * _object, Method _method) : mObject(_object), mMethod(_method) { }
virtual bool isType( const std::type_info& _type) { return typeid(CMethodDelegate) == _type; }
virtual void invoke()
{
(mObject->*mMethod)();
}
virtual bool compare(IDelegate *_delegate) const
{
if (0 == _delegate || !_delegate->isType(typeid(CMethodDelegate)) ) return false;
CMethodDelegate* cast = static_cast(_delegate);
return cast->mObject == mObject && cast->mMethod == mMethod;
}
private:
T * mObject;
Method mMethod;
};

首先解释一下:因为类成员函数指针与类的类型有关,不同类的成员函数指针是不一样的。

要解决类型不同,很简单,使用模板就行。

代码跟CStaticDelegate基本一样,下面稍微解释一下:

CMethodDelegate类主要封装了一个类实例指针以及类成员函数的指针

这样在invoke时就不要额外的通过一个类实例了

要注意一点,compare函数的实现中,相等判定是类实例以及类函数指针都一样。

也就是说就算是指针同一个成员函数,但实例不同,委托就不同

为了方便使用,定义函数newDelegate来创建委托使用的函数

copy to clipboardprint inline IDelegate* newDelegate( void (*_func)() )
{
return new CStaticDelegate(_func);
}
template
inline IDelegate* newDelegate( T * _object, void (T::*_method)() )
{
return new CMethodDelegate(_object, _method);
}
inline IDelegate* newDelegate( void (*_func)() )
{
return new CStaticDelegate(_func);
}
template
inline IDelegate* newDelegate( T * _object, void (T::*_method)() )
{
return new CMethodDelegate(_object, _method);
}

至此,对C++函数指针的封装就完成了,不难吧。

下面就是委托的实现了

copy to clipboardprint class CMultiDelegate
{
public:
typedef std::list ListDelegate;
typedef ListDelegate::iterator ListDelegateIterator;
typedef ListDelegate::const_iterator ConstListDelegateIterator;
CMultiDelegate () { }
~CMultiDelegate () { clear(); }
bool empty() const
{
for (ConstListDelegateIterator iter = mListDelegates.begin(); iter!=mListDelegates.end(); ++iter)
{
if (*iter) return false;
}
return true;
}
void clear()
{
for (ListDelegateIterator iter=mListDelegates.begin(); iter!=mListDelegates.end(); ++iter)
{
if (*iter)
{
delete (*iter);
(*iter) = 0;
}
}
}
CMultiDelegate& operator+=(IDelegate* _delegate)
{
for (ListDelegateI