1、类模板
template < typename T>
class complex {
complex ( T r = 0 , T i = 0 )
: re ( r) , im ( i) { }
complex& operator + = ( const complex& ) ;
T real ( ) const { return re; }
T imag ( ) const { return im; }
private :
T re, im;
} ;
complex< double > c1 ( 1 , 1 , 2.0 ) ;
complex< int > c2 ( 2 , 5 ) ;
2、 函数模板
template < typename T>
const T& min ( const T& a, const T& b) {
return a > b ? b : a;
} ;
3、成员模板
template < typename T1, typename T2>
struct pair {
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair ( ) : first ( T1 ( ) ) , second ( T2 ( ) ) { }
pair ( const T1& a, const T2& b)
: first ( a) , second ( b) { }
template < typename U1, typename U2>
pair ( const pair< U1, U2> & p)
: first ( p. first) , second ( p. second) { }
} ;
pair< Derived1, Derived2> p;
pair< Base1, Base2> p2 ( p) ;
4、模板特化
template < typename Key>
struct hash { } ;
template < >
struct hash< char > {
size_t operator ( ) ( char x) const { return x; }
} ;
template < >
struct hash< int > {
size_t operator ( ) ( int x) const { reuturn x; }
} ;
5、 模板的偏特化
template < typename T, typename Alloc= . . . >
class vector {
. . .
} ;
template < typename Alloc= . . . >
class vector < bool , Alloc> {
. . .
} ;
template < typename T>
class C {
. . .
} ;
template < typename T>
class C < T* > {
. . .
} ;
C< string> obj1;
C< string* > obj2;
6、 模板的模板参数
template < typename T, template < typename T> class container >
class Sample {
private :
Container< T> c;
public :
. . .
} ;
Sample< std:: string, list> mylist1;
template < typename T>
using Lst = std:: list< T, allocator< T>> ;
Sample< std:: string, Lst> mylist2;
template < class T , class Sequence = deque< T>>
class stack {
friend bool operator == < > ( const stack& , const stack& ) ;
friend bool operator < < > ( const stack& , const stack& ) ;
protected :
Sequence c;
. . .
}
stack< int > s1;
stack< int , list< int >> s2;
7、参数个数可变模板(variadic templates)
void print ( ) { }
template < typename T, typename . . . Types>
void print ( const T& firstArg, const Types& . . . args) {
std:: cout<< firstArg<< std:: endl;
std:: cout<< "剩余参数个数: " << sizeof . . . ( args) << std:: endl;
print ( args. . . ) ;
}
print ( 7.5 , "hello" , bitset< 16 > ( 377 ) , 42 ) ;