问题的提出
类模板的定义
template <class 类型参数1, class 类型参数2, ...> // 类型参数表class 类模板名 {成员函数和成员变量};
成员函数的写法
template <typename 类型参数1, class 类型参数2, ...> // 类型参数表返回值类型 类模板名<类型参数名列表>::成员函数名(参数表) {...}
定义对象的写法
类模板名 <真实类型参数表> 对象名(构造函数实参表)
模板类示例:Pair类模板
template <class T1, class T2>class Pair {public:T1 key;T2 value;Pair(T1 k, T2 v):key(k), vaule(v) {}bool operator < (const Pair<T1, T2> & p) const;}template<class T1, class T2>bool Pair<T1, T2>::operator < (const Pair<T1, T2> & p) const {return key < p.key;}void main() {Pair<string, int> student("Tom", 19);// 实例化出一个类 Pair<string, int>cout << student.key << " " << student.value;}
用类模板定义对象
编译器由类模板生成类的过程交类模板的实例化。由类模板实例化得到的类,叫模板类
- 同一个类模板的两个模板类是不兼容的
Pair<string, int > * p;Pair<string, double> a;p = & a; // wrong
函数模板作为类模板的成员
#include <iostream>using namespace std;template <class T>class A {public:template<class T2>void Func(T2 t) { cout << t; } // 成员函数模板}void main() {A<int> a;a.Func('K'); // 成员函数模板 Func被实例化a.Func("hell"); // 成员函数模板 Func被再次实例化} // 输出 KHello
类模板与非类型参数
template <class T, int size>class CArray {T array[size];public:void Print() {for(int i = 0; i < size; ++i)cout << array[i] << endl;}};CArray<double 40> a2;CArray<int 50> a3;
