ATL-Style模板 不用虚函数实现多态

    以前看过ATL/WTL,发现它特有的实现方式不错,于是决定在项目当中使用上。通过《WTL开发指南》发现其中有严重的错误(痛恨这种极其不负责的指导方式,容易产生误导),这些特意做个笔记。其主旨在于:用类模板来实现多态,子类通过类模板将真实的类型传给父类,这样父类就知其真实的类型,并调用相关方法,同时又可以通过类的继承了解到应实现哪些"覆盖“的方法。

    其代码转载自:http://blog.csdn.net/nyzhl/archive/2009/07/28/4387675.aspx

 注:以下代码在AIX及Windows(VS2005)下测试通过。其中书中主要的严重错误在于:子类定义体中应声明父类模板实例为其友元类

1 #include <stdio.h>
2
3 template<class T>
4 class CBase
5 {
6 public:
7 void Display()
8 {
9 T* pT = static_cast<T*>(this);
10 pT->Print();
11 }
12 protected:
13 void Print()
14 {
15 printf("This is CBase class\n");
16 }
17 };
18
19 class CBaseClass:public CBase<CBaseClass>
20 {
21 friend class CBase<CBaseClass>;
22 };
23
24 class CDerivedClass:public CBase<CDerivedClass>
25 {
26 friend class CBase<CDerivedClass>;
27 protected:
28 void Print()
29 {
30 printf("This is CDerived class\n");
31 }
32 };
33
34 int main(int argc,char *argv[])
35 {
36 CBaseClass base;
37 CDerivedClass derived;
38 base.Display();
39 derived.Display();
40 return 0;
41 }

posted @ 2011-06-02 13:01  lingjip  Views(794)  Comments(0Edit  收藏  举报