模板定义以关键字template开始,后接模板形参表,模板形参表是用尖括号扩住的一个或多个模板形参的列表,形参之间以逗号分隔。
模板形参表不能为空。
模板形参可以是表示类型的类型形参,也可以是表示常量表达式的非类型形参。类型形参跟在关键字class或typename之后定义。在函数模板形参表中,class和typename的意义是一样的,都指出后面所接的名字表示一个类型。
如果是类型形参,该形参表示未知类型,如果是非类型形参,它是一个未知值。
1. inline函数模板
说明符放在模板形参表之后、返回类型之前,不能放在关键字template之前。
template <typename T> inline T min(const T&, const T&); //ok
inline template <typename T> T min(const T&, const T&); //error
2. 类模板
template <class Type> class Queue {
public:
Queue();
Type &front(); //return element from head of Queue
const Type &front() const;
void push(const Type &); //add element from head of Queue
void pop(); //remove element from head of Queue
bool empty() const; // true if no elements in the Queue
private:
};
使用类模板时,必须为模板形参显示指定实参:
Queue<int> qi; //queue that holds ints
Queue< vector<double> > qc; //queue that holds vectors of doubles
Queue<string> qs; //queue that holds strings