软件架构设计之Utility模块――Functor(二)
IsSameType::value ||
HTIsSameType::value ||
HTIsSameType::value
};
enum { isReference = HTIsReference::value };
private:
template
struct AdjReference
{
template
struct In { typedef U const & Result; };
};
template<>
struct AdjReference
{
template
struct In { typedef U Result; };
};
typedef typename AdjReference::
template In::Result AdjType;
// 正确的选择函数参数的类型
// 对于精巧型(有构造函数和析构函数额外调用)采用引用传参数,对于纯量型(数值型别,枚举型别,指针,指向成员的指针)采用直接传值
typedef typename HTSelect::value, AdjType, T>::Result ParmType;
};
四:HTFunctor
HTTypeList及HTTypeTraits提供我们强大的功能。这让我们实作HTFunctor更加的方便。下面直接看代码。
[cpp]
// Functor对象明显是个小对象,这里采用小对象分配器
// 使用了Command模式及IMPL模式
template
struct HTFunctorImplBase : public HTSmallObject<>
{
typedef R ResultType;
typedef HTEmptyType Parm1;
typedef HTEmptyType Parm2;
};
template
struct HTFunctorImpl;
// 无参数版本
template
struct HTFunctorImpl : public HTFunctorImplBase
{
typedef R ResultType;
virtual ResultType operator()(ObjClass* pObj) = 0;
virtual HTFunctorImpl* Clone() const = 0;
virtual ~HTFunctorImpl() {}
};
// 一个参数版本
template
struct HTFunctorImpl : public HTFunctorImplBase
{
typedef R ResultType;
typedef typename HTTypeTraits::ParmType Parm1;
virtual ResultType operator()(Parm1, ObjClass* pObj) = 0;
virtual ~HTFunctorImpl() {}
};
// 两个参数版本
template
struct HTFunctorImpl : public HTFunctorImplBase
{
typedef R ResultType;
typedef typename HTTypeTraits::ParmType Parm1;
typedef typename HTTypeTraits::ParmType Parm2;
virtual ResultType operator()(Parm1, Parm2, ObjClass* pObj) = 0;
virtual HTFunctorImpl* Clone() const = 0;
virtual ~HTFunctorImpl() {}
};
// 可调用体(即封装的处理函数)为仿函数
template
class HTFunctorHandler :
public HTFunctorImpl
<
typename ParentFunctor::ResultType,
typename ParentFunctor::ParmList,
ObjClass
>
{
typedef typename ParentFunctor::Impl Base;
public:
typedef typename Base::ResultType ResultType;
typedef typename Base::Parm1 Parm1;
typedef typename Base::Parm1 Parm2;
HTFunctorHandler(const Fun& fun) : m_fun(fun) {}
HTFunctorHandler* Clone() const { return new HTFunctorHandler(*this); }
ResultType operator()(ObjClass* pObj)
{ return m_fun(); }
ResultType operator()(Parm1 p1, ObjClass* pObj)
{ return m_fun(p1); }
ResultType operator()(Parm1 p1, Parm2 p2, ObjClass* pObj)
{ return m_fun(p1, p2); }
private:
Fun m_fun;
};
// 可调用体(即封装的处理函数)为类成员函数,调用需传递对象指针
template
class HTMemFunHandler :
public HTFunctorImpl
<
typename ParentFunctor::ResultType,
typename ParentFunctor::ParmList,
ObjClass
>
{
typedef typename ParentFunctor::Impl Base;
public:
typedef typename Base::ResultTy