1>显式具体化
显式具体化也是基于函数模板的,只不过在函数模板的基础上,添加一个专门针对特定类型的、实现方式不同的具体化函数。
[cpp] view plain copy
template<>void swap
{
int salary;
salary = a.salary;
a.salary = b.salary;
b.salary = salary;
}
如上所示,该具体化函数的实现与模板并不一致,编译器解析函数调用时会选择最匹配的函数定义。
2>定义同名常规函数
[cpp] view plain copy
void swap(job &a, job &b)
{
int salary;
salary = a.salary;
a.salary = b.salary;
b.salary = salary;
}
由于编译器在重载解析时,会选择最匹配函数定义,所以在调用swap(jobA, jobB)时,编译器会选择void swap(job &a, job &b)函数定义,而屏蔽了模板函数。
同时,模板函数也可以重载,其操作与常规函数一致。
[cpp] view plain copy
template
template
template
{
T temp;
temp = a;
a = b;
b = temp;
}
template
{
T temp;
temp = a;
a = b;
b = c;
c = temp;
}
上面主要说的是函数模板的具体化,下面说下模板实例化。
函数模板:
[cpp] view plain copy
#define MAXNAME 128
struct job
{
char name[MAXNAME]:
int salary;
};
template
void swap(T &a, T &b )
{
T temp;
temp = a;
a = b;
b = temp;
};
template void swap
template<> void swap
{
int salary:
salary = a.salary:
a.salary = b.salary;
b.salary = salary;
};//explicite specialization.
类模板:
[cpp] view plain copy
template
class Arrary
{
private:
T* ar;
int l;
...
};//template class declaration.
template class Array
template<> class Array
{
private:
job* ar;
int l;
};//expicit specialization. 显式具体化,类定义体可以不同于类模板Array
相应的,隐式实例化指的是:在使用模板之前,编译器不生成模板的声明和定义实例。只有当使用模板时,编译器才根据模板定义生成相应类型的实例。如:
int i=0, j=1;
swap(i, j); //编译器根据参数i,j的类型隐式地生成swap
Array
显式实例化:
当显式实例化模板时,在使用模板之前,编译器根据显式实例化指定的类型生成模板实例。如前面显示实例化(explicit instantiation)模板函数和模板类。其格式为:
template typename function
template class classname
显式实例化只需声明,不需要重新定义。编译器根据模板实现实例声明和实例定义。
显示具体化:
对于某些特殊类型,可能不适合模板实现,需要重新定义实现,此时可以使用显示具体化(explicite specialization)。显示实例化需重新定义。格式为:
template<> typename function
template<> class classname
综上:
template<> void swap
template void swap