C++ 模板实例化

来源:互联网 发布:斗直播软件 编辑:程序博客网 时间:2024/06/05 08:25

16.2. Instantiation

A  template is a blueprint; it is not itself aclass or a function. The compiler uses the template to generate type-specificversions of the specified class or function. The process of generatng a type-specificinstance of a template is known as instantiation. The term reflects the notion that a new"instance" of the template type or function is created.

A  template is instantiated when we use it. Aclass template is instantiated when we refer to the an actual template classtype, and a function template is instantiated when we call it or use it to initializeor assign to a pointer to function.

 

Instantiating a Class

When wewrite

Queue<int>qi;

the compilerautomatially creates a class named Queue<int>. In effect, the compilercreates the Queue<int>class by rewriting the Queuetemplate, replacing everyoccurrence of the template parameter Typeby the type int. The instantiatedclass is as if we had written:

 

// simulated version of Queueinstantiated for type int

template <class Type> classQueue<int> {

public:

Queue(); // this bound toQueue<int>*

int &front(); // return typebound 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 invariantcode

private:

// ...

};

 

Class Template Arguments Are Required

ClassTemplate Arguments Are Required

When we wantto use a class template, we must always specify the template arguments explicitly.

Queue qs; //error: which template instantiation?

A  class template does not define a type; only aspecific instantiation defines a type. We define a specific instantiation byproviding a template argument to match each template parameter.

Templatearguments are specified in a comma-separated list and bracketed by the (<)and (>) tokens:

Queue<int>qi; // ok: defines Queue that holds ints

Queue<string>qs; // ok: defines Queue that holds strings

The typedefined by a template class always includes the template argument(s). Forexample, Queueis not a type; Queue<int>or Queue<string>are.

 

Function-Template Instantiation

When we usea function template, the compiler will usually infer the template arguments forus:

 

int main()

{

compare(1, 0); // ok: binds templateparameter to int

compare(3.14, 2.7); // ok: bindstemplate parameter to double

return 0;

}

 

This programinstantiates two versions of compare: one where Tis replaced by intand the otherwhere it is replaced by double. 

0 0