C++ 定义类模板

16.1.2. Defining a Class Template

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:
// ...
};


A  class template is a template, so it must begin with the keyword templatefollowed by a template parameter list. Our Queuetemplate takes a single template type parameter named Type.


With the exception of the template parameter list, the definition of a class template looks like any other class. A class template may define data, function, and type members; it may use access labels to control access to those members; it defines constructors and destructors; and so on.In the definition of the class and its members, we can use the template parameters as stand-ins for types or values that will be supplied when the class is used.


Using a Class Template

In contrast to calling a function template, when we use a class template, we must explicitly specify arguments for the template parameters:


Queue<int> qi; // Queue that holdsints
Queue< vector<double> > qc; // Queue that holds vectors of doubles
Queue<string> qs; // Queue that holds strings


The compiler uses the arguments to instantiate a type-specific version of the class. Essentially,
the compiler rewrites our Queueclass replacing Typeby the specified actual type provided by the
user. In this case, the compiler will instantiate three classes: a version of Queuewith Type
replaced by int, a second Queueclass that uses vector<double>in place of  Type, and a third
that replaces  Typeby string.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值