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

2014-11-24 12:26:57 · 作者: · 浏览: 3

16.4.1 类模板成员函数

类模板成员函数的定义具有如下形式:

必须以关键字template开头,后接类的模板形参表。

必须指出它是哪个类的成员。

类名必须包含其模板形参。

1.destroy函数

template void Queue::destroy(){
while(!empty())
pop();
}
template void Queue::destroy(){
while(!empty())
pop();
}2. pop函数

template void Queue::pop()
{
QueueItem p=head;
this->head=this->head->next;
delete p;
}
template void Queue::pop()
{
QueueItem p=head;
this->head=this->head->next;
delete p;
}3. push函数

template void Queue::push(const Type &p)
{
QueueItem *pt=new QueueItem(p);
if(empty())
head=tail=pt;
else{
this->tail->next=pt;
tail=pt;
}
}
template void Queue::push(const Type &p)
{
QueueItem *pt=new QueueItem(p);
if(empty())
head=tail=pt;
else{
this->tail->next=pt;
tail=pt;
}
}4. copy_elems函数

template
void Queue::copy_elems(const Queue &orig){
for(QueueItem *pt=orig.head;pt==0;pt=pt->next)
{
push(pt->item);
}
}
template
void Queue::copy_elems(const Queue &orig){
for(QueueItem *pt=orig.head;pt==0;pt=pt->next)
{
push(pt->item);
}
}5. 类模板成员函数的实例化

类模板的成员函数本身也是函数模板。像其他任何函数模板一样,需要使用类模板的成员函数产生该成员的实例化。与其他函数模板不同的是,在实例化类模板成员函数的时候,编译器不执行模板实参推断,相反,类模板成员函数的模板形参由调用该函数的对象的类型确定。

6. 何时实例化类和成员

类模板的成员函数只有为程序所用才进行实例化。如果某函数从未使用,则不会实例化该成员函数。

摘自 xufei96的专栏