第16章 模板与泛型编程(11)

2014-11-24 12:26:51 · 作者: · 浏览: 4

16.4.5 成员模板

任意类(模板或非模板)可以拥有本身为类模板或函数模板的成员,这种成员称为成员模板(member template),成员模板不能为虚。

1. 定义成员模板


template
class Queue{
public:
Queue():head(0), tail(0){}
Queue(const Queue &Q):head(0), tail(0)
{copy_elems(Q);}
Queue& operator=(const Queue&);
~Queue(){destroy();}
Type& front()
{return head->item;}
const Type &front() const{return head->item;}
void push(const Type &);
void pop();
bool empty() const
{return head==0;}
friend ostream &operator<< (ostream &os, const Queue &q);

template
Queue(It beg, It end):head(0), tail(0){copy_elems(beg,end)}
template
void assign(Iter, Iter);
private:
QueueItem *head;
QueueItem *tail;
void destroy();
void copy_elems(const Queue&);
template
void copy_elems(Iter,Iter);
};
template
class Queue{
public:
Queue():head(0), tail(0){}
Queue(const Queue &Q):head(0), tail(0)
{copy_elems(Q);}
Queue& operator=(const Queue&);
~Queue(){destroy();}
Type& front()
{return head->item;}
const Type &front() const{return head->item;}
void push(const Type &);
void pop();
bool empty() const
{return head==0;}
friend ostream &operator<< (ostream &os, const Queue &q);

template
Queue(It beg, It end):head(0), tail(0){copy_elems(beg,end)}
template
void assign(Iter, Iter);
private:
QueueItem *head;
QueueItem *tail;
void destroy();
void copy_elems(const Queue&);
template
void copy_elems(Iter,Iter);
};2. 在类外部定义成员模板

当在类模板作用域外部定义成员模板的时候,必须包含两个模板形参表。


template
template
void Queue::assign(Iter beg, Iter end){
destroy();
copy_elems(beg,end);
}
template
template
void Queue::assign(Iter beg, Iter end){
destroy();
copy_elems(beg,end);
}因为assign函数删除现存容器中的成员,所以传给assign函数的迭代器有必要引用不同容器中的元素。标准容器的assign成员和迭代器构造函数有相同的限制。

3. 成员模板遵循常规访问控制

成员模板遵循与任意其他类成员一样的访问规则。

4. 成员模板和实例化

与其他成员一样,成员模板只有在程序中使用时才实例化。成员模板有两种模板形参:由类定义的和由成员模板本身定义的。类模板形参由调用函数的对象的类型确定,成员定义的模板形参的行为和普通函数模板一样,这些形参都通过常规模板实参推断而确定。

摘自 xufei96的专栏