摘自C++ primer plus 中文第六版
如果不考虑向后兼容的问题,并愿意键入较长的单词,声明参数是应该使用typename而不是class。
模板显示具体化
对于给定的函数名,可以有非模板函数,模板函数和显示具体化模板函数集他们的重载 版本。
显示具体化的原型和定义应该以template<>打头 ,并通过名称来指出类型。
具体化优先于常规模板,而非模板函数优先于具体化和常规模板。
举例:
class job
{
char name[32];
double salary;
int floor
};
非模板函数:
voidf swap(job &a,job&b)
{
job temp = a;
a = b;
b = temp;
}
模板类型:
template <typename T>
void swap(T &a, T&b)
{
T temp = a;
a = b;
b = temp;
}
具体实例化:
template <> void swap<job>(job&a, job&b)
{
double s;
int f;
s = a.salary;
a.salary = b.salary;
b.salary =s;
f = a.floor;
a.floor = b.floor;
b.floor = f;
}
关键字decltype
1.在函数模板中定义左值需要确定类型但类型未知的时候:
例:
int x;
decltype(x) y;//make y the same type as x
例:
template <class T1, class T2>
void ft(T1 x, T2 y)
{
...
?type? xpy = x+y;
}
decltype(x + y) xpy = x + y;
auto 返回值类型函数声明语法:
原型为下列表达式的语法:
double h(int x. float y);
使用新增语法可写为
auto h(int x, float y) -> double;
这将返回值类型移到了参数声明后面,->double被称为后置返回值类型,其中auto是一个占位符,表示后置返回值类型提供的类型,这是C++11给auto新增的一种角色,这种语法也可以用于函数定义:
auto h(int x, float y)->double
{
/* function body */
}
通过结合decltype ,便可以给gt()指定返回值类型,例如:
template <class T1, class T2>
auto gt(T1 x, T2 y) ->delctype(x + y)
{
...
return x + y;
}