函数模板(1)

1:函数模板就是通用函数的简称:泛型可用int,double替换,通过将类型作为参数传递给模板,使编译器生成该类型的函数。
int x;
short interval;
转换
double x;
short doubleerval;

2:函数模板允许以任何类型的方式来定义函数:

template  <typename anytype>//template和typename为关键字
void swap(anytype &a;anytype &b)
{
   anytype  temp;
   temp=a;
   a=b;
   b=temp;
   }

如果需要多个将程序用于同一种一个特定类型的函数,使用模板;不考虑兼容问题,并愿意键入较长的单词,声明类型参数时,使用typename,而不是class。

二:重载的模板:
对多个不同类型的函数使用同一种算法的函数时,可使用模板。
#include
template
void swap(T a[],T b[],int n)
{
T temp;
for(int i=0;i<n;i++)
{
temp =a[i];
a[i]=b[i];
b[i]=temp;
}
}
重载的模板特征为(T[],T[],int)
最后一个参数类型为int,即具体的类型。

显式具体化
struct job
{
char name[40];
double salary;
int floor;
}
void swap(job&,job&);
template
void swap(T&,T&);
template<>void swap(job &,job &);
显示具体化的原型和定义应以template<>开头,并以名称来指出函数。

猜你喜欢

转载自blog.csdn.net/weixin_43360397/article/details/85217086