1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <cassert> 

using namespace std;

struct Object
{ 
   public: bool xxx; 
   public: int yyy; 
};

struct A1 : public Object
{  };

struct B1 : public Object
{  };

struct C1 : public Object
{  };

A1 *Aaa = 0;
B1 *Bbb = 0;
C1 *Ccc = 0;

void usePolymorphism( Object *&ptr )
{
   ptr = 0;        
}

template <typename InstanceType, typename ClassType>
void useTemplate( ClassType *&ptr )
{
   ptr = new InstanceType();     
   
   ptr->xxx = true;
   ptr->yyy = 2;  
} 

int main()
{

   // 使用多型 
   usePolymorphism( Aaa ); // error ! invalid initialization of reference of 
                           // type 'Object*&' from expression of type 'A1*'
    
   useTemplate<A1>( Aaa );
   useTemplate<B1>( Bbb );
   useTemplate<C1>( Ccc ); 
   
   assert( Aaa != 0 && Bbb != 0 && Ccc != 0 &&
           "all pointers should been initialized" ); 
   
   delete Aaa;
   delete Bbb;
   delete Ccc;
    
   cin.get();
}// end of function 'main'