很久以前就喜欢上了模板编程,当接触到ATL风格的模板时更是觉得惊艳。典型的ATL模板如下所示:
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> template < typename TDerive >
class CBaseT
{
public :
void InitBaseMethod()
{
TDerive * pThis = static_cast < TDerive *> ( this );
pThis -> InitDeriveMethod();
}
};
class CDerive : public CBaseT < CDerive >
{
public :
void InitDeriveMethod()
{
AtlMessageBox( NULL, _T( " CDerive::InitDeriveMethod " ) );
}
};
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> template < typename TDerive >
class CBaseT
{
public :
void InitBaseMethod()
{
TDerive * pThis = static_cast < TDerive *> ( this );
pThis -> InitDeriveMethod();
}
};
class CDerive : public CBaseT < CDerive >
{
public :
void InitDeriveMethod()
{
AtlMessageBox( NULL, _T( " CDerive::InitDeriveMethod " ) );
}
};
这种风格我到现在看来还是觉得很疯狂,用派生类作为基类的模板参数,我想实作出这样代码的牛人当时肯定处于暴走状态啊,也许真正的牛人每天都处于我所理解的暴走状态的.
作为一个小小程序员,我没有这样的创意,但我能模仿,能经常在自己的程序中应用.不过,最近我有研究ATL的源码(COM实现),才发现我连运用也用的不够彻底.这种风格的模板完全可以实现在一个基类中调用另一个基类的方法。我也不知道我这种惊奇在各位大侠看来是不是有点鸡肋.可能是我的变通能力差吧.
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> class CBaseOther
{
public :
void InitBaseOther()
{
AtlMessageBox( NULL, _T( " CBaseOther::InitBaseOther " ) );
}
};
template < typename TDerive >
class CBaseT
{
public :
void InitBaseMethod()
{
TDerive * pThis = static_cast < TDerive *> ( this );
// 调用CBaseOther的InitBaseOther方法
pThis -> InitBaseOther();
}
};
class CDerive : public CBaseT < CDerive > , public CBaseOther
{
public :
void InitDeriveMethod()
{
AtlMessageBox( NULL, _T( " CDerive::InitDeriveMethod " ) );
}
};
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> class CBaseOther
{
public :
void InitBaseOther()
{
AtlMessageBox( NULL, _T( " CBaseOther::InitBaseOther " ) );
}
};
template < typename TDerive >
class CBaseT
{
public :
void InitBaseMethod()
{
TDerive * pThis = static_cast < TDerive *> ( this );
// 调用CBaseOther的InitBaseOther方法
pThis -> InitBaseOther();
}
};
class CDerive : public CBaseT < CDerive > , public CBaseOther
{
public :
void InitDeriveMethod()
{
AtlMessageBox( NULL, _T( " CDerive::InitDeriveMethod " ) );
}
};
唯一的遗憾就是对于派生类重写过的虚方法,在模板基类中就没有办法调用到基类相应的虚方法了.毕竟模板基类和别的基类之间不存在继承关系