8-5 函数模板

8.5 函数模板

8.5.1介绍

通过将类型隐式传入函数,编译器自动生成该类型的函数

8.5.2使用案例

template <typename Anytype>
void Swap(Anytype &a,Anytype &b)
{
Anytype temp;
temp=a;
a=b;
b=temp;
}
//格式:template <typename 使用的模板参数名称>
//参数列表(使用的模板参数名称 形参...)

8.5.3模板的局限性

如果某些类型不支持某些运算,则模板将无法使用

例如:

对数组进行=赋值

对结构进行>比较

8.5.4显式具体化

在模板之外,针对某些特定类型的匹配的函数时,将直接选用该函数。

优先级

常规函数>具体化函数>模板函数

语法
template <> void Swap(int,int);
template <> void Swap<int>(int,int); //声明模板参数为int

等价的写法,只是便于阅读,可省略

用法案例
template <typename T>
void Swap(T &a,T &b);

template <> void Swap(job &a,job &b);

int main()
{
return 0;
}

template <typename T>
void Swap(T &a,T &b)
{
T temp;
temp=a;
a=b;
b=temp;
}

template <> void Swap(job &a,job &b)
{
int temp;
temp=a.money;
a.money=b.money;
b.money=temp;
double temp2;
temp2=a.floor;
a.floor=b.floor;
b.floor=temp;
}

8.5.5显式实例化

根据参数类型进行实例化称为隐式实例化

而显式实例化是指将模板的参数类型指定

语法

在声明所需的种类——用<>指示类型,并在声明前加上关键字template:

template void Swap<int>(int,int);//template后无<>
使用
Swap<int>(i,j);

8.5.6一些问题的解决

函数中变量类型不定
template<class T1,class T2>
void ft(T1 x,T2 y)
{
...
?type? xpy=x+y;//xpy的类型不能确定
...
}

解决办法(c++11):关键字decltype

语法

decltype(expression) var

注:

1.expression可以为变量、表达式、函数返回类型(不会实际调用函数)

2.decltype(expression)代表一个类型声明符,可用typedef来简写,例如:typedef decltype(x+y) xytype;

例子
template<class T1,class T2>
void ft(T1 x,T2 y)
{
...
decltype(x+y) xpy=x+y;//xpy的类型不能确定
...
}
函数返回值不确定
template<class T1,class T2>
?type? gt(T1 x,T2 y)
{
...
return x+y;//返回值的类型不确定
}

解决办法(c++11):后置返回值类型并配合decltype使用

(aoto新的用法)

语法
auto h(int x,int y)->double
{
...
}
例子
template<class T1,class T2>
auto gt(T1 x,T2 y)->decltype(x+y)
{
...
return x+y;//返回值的类型不确定
}