ATL初学-2 :感悟ATL风格的模板

很久以前就喜欢上了模板编程,当接触到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 " ) );
    }
};

这种风格我到现在看来还是觉得很疯狂,用派生类作为基类的模板参数,我想实作出这样代码的牛人当时肯定处于暴走状态啊,也许真正的牛人每天都处于我所理解的暴走状态的.

作为一个小小程序员,我没有这样的创意,但我能模仿,能经常在自己的程序中应用.不过,最近我有研究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 " ) );
    }
};

 

唯一的遗憾就是对于派生类重写过的虚方法,在模板基类中就没有办法调用到基类相应的虚方法了.毕竟模板基类和别的基类之间不存在继承关系

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值