模板是一个蓝图,它本身不是类或函数。编译器用模板产生指定的类或函数的特定类型版本。产生模板的特定类型实例的过程称为实例化。
模板在使用时将进行实例化,类模板在引用实际模板类类型时实例化,函数模板在调用它或用它对函数指针进行初始化或赋值时实例化。
类的实例化
模板的定义:
template <class Type> class Queue {
public:
Queue (); // default constructor
Type &front (); // return element from head of Queue
const Type &front () const;
void push (const Type &); // add element to back 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 的类。实际上,编译器通过重新编写 Queue 模板,用类型 int 代替模板形参的每次出现而创建 Queue 类。实例化的类就像已经编写的一样:
// simulated version of Queue instantiated for type int
class Queue<int> {
public:
Queue(); // this bound to Queue<int>*
int &front(); // return type bound to int
const int &front() const; // return type bound to int
void push(const int &); // parameter type bound to int
void pop(); // type invariant code
bool empty() const; // type invariant code
private:
// ...
};
Queue<int> qi;
Queue qi; //error
用模板类定义的类型总是模板实参。例如,Queue 不是类型,而 Queue<int> 或 Queue<string> 是类型
函数模板实例化
使用函数模板时,编译器通常会为我们推断模板实参
int main()
{
compare(1, 0); // ok: binds template parameter to int
compare(3.14, 2.7); // ok: binds template parameter to double
retu