代码小技巧

先上一段代码:
class  CTagBase
{
public:
    
virtual ~CTagBase()
    {}

    
virtual  void  Init()  =  0;
};

#define  MakeDeriveClass( XDerive )        \
            
class  XDerive : public CTagBase        \
            {        \
            
public:        \
                
virtual  void  Init()        \
                {  AtlMessageBox( NULL, __FUNCTION__  ); }  \
            };

MakeDeriveClass( CMacroDeriveFromBase1 )
MakeDeriveClass( CMacroDeriveFromBase2 )
MakeDeriveClass( CMacroDeriveFromBase3 )

CMacroDeriveFromBase1  macroDerive1;
CMacroDeriveFromBase2  macroDerive2;
CMacroDeriveFromBase3  macroDerive3;

macroDerive1.Init();
macroDerive2.Init();
macroDerive3.Init();
此代码利用宏创建了CMacroDeriveFromBase1CMacroDeriveFromBase2CMacroDeriveFromBase3三个类,这3个类的结构是一样的。从某种意义上说,此时宏方便了我们编码,但是调试时的确不直观了.下面用模板的tag手法重构一下:
template<typename>
class  CTagDerive : public CTagBase
{
public:
    
virtual  void  Init()
    { AtlMessageBox( NULL, __FUNCTION__  ); }
};

struct  STagDeriveFromBase1_Tag 
{};
typedef  CTagDerive
<STagDeriveFromBase1_Tag>  CTagDeriveFromBase1;

struct  STagDeriveFromBase2_Tag 
{};
typedef  CTagDerive
<STagDeriveFromBase1_Tag>  CTagDeriveFromBase2;

struct  STagDeriveFromBase3_Tag 
{};
typedef  CTagDerive
<STagDeriveFromBase1_Tag>  CTagDeriveFromBase3;



CTagDeriveFromBase1  tagDerive1;
CTagDeriveFromBase2  tagDerive2;
CTagDeriveFromBase3  tagDerive3;

tagDerive1.Init();
tagDerive2.Init();
tagDerive3.Init();
tag手法可以看作trait手法的一种简化,目的在于产生不同的类型.
posted @ 2009-08-11 11:29  孤竹君  阅读(263)  评论(0编辑  收藏  举报