3.4 Partial Specialization

Ru-Brd

Class templates can be partially specialized. You can specify special implementations for particular circumstances, but some template parameters must still be defined by the user . For example, for the following class template

 template <typename T1, typename T2>  class MyClass {   }; 

the following partial specializations are possible:

  // partial specialization: both template parameters have same type  template <typename T>  class MyClass<T,T> {   };  // partial specialization: second type is  int  template <typename T>  class MyClass<T,int> {   };  // partial specialization: both template parameters are pointer types  template <typename T1, typename T2>  class MyClass<T1*,T2*> {   }; 

The following example shows which template is used by which declaration:

 MyClass<int,float> mif;  // uses  MyClass<T1,T2>  MyClass<float,float> mff;  // uses  MyClass<T,T>  MyClass<float,int> mfi;  // uses  MyClass<T,int>  MyClass<int*,float*> mp;  // uses  MyClass<T1*,T2*> 

If more than one partial specialization matches equally well, the declaration is ambiguous:

 MyClass<int,int> m;  // ERROR: matches  MyClass<T,T>  //        and  MyClass<T,int>  MyClass<int*,int*> m;  // ERROR: matches  MyClass<T,T>  //        and  MyClass<T1*,T2*> 

To resolve the second ambiguity, you can provide an additional partial specialization for pointers of the same type:

 template <typename T>  class MyClass<T*,T*> {   }; 

For details, see Section 12.4 on page 200.

Ru-Brd


C++ Templates
C++ Templates: The Complete Guide
ISBN: 0201734842
EAN: 2147483647
Year: 2002
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net