自C++11起,template 可以拥有那种“得以接受个数不定之 template 实参”的参数。此能力称为 variadic template (可变参数宏)。例如,对于print()函数,得以在调用它时给予不定个数的实参且各具不同类型:
void print()
{
std::cout << "执行无参print()" << std::endl;
}
template<typename T,typename... Types>
void print(const T& firstArg, const Types&...args)
{
std::cout << firstArg << std::endl;
print(args...);
std::cout << "执行含实参print()"<< endl;
}
int main()
{
print(7.5, "hello", 42);
return 0;
}
运行结果如图。
由此可知,如果传入一个或多个实参,上述的 function template(函数模板),它会把第一个实参与其它实参区分开来,允许第一个实参被打印,然后通过递归调用 printf() 并传入后续其余实参。对于这个 template ,你必须重载函数 print() ,才能结束整个递归行为。
Alias Template(带别名的模板,或者称之为 Template Typedef)
自C++11起,支持 template(partial) type definition (模板类型定义)然而由于关键字 typename 用于此处时总是出于某种原因而失败,所以这里引入关键字 using ,并因此引入一个新术语 alias template 。例如:
在定义如下的语句后:
template<typename T>
using Vec = std::vector<T, MyAlloc<T>>;
Vec<int> coll;
等价于
std::vector<int ,MyAlloc<int>> coll;
其他的 Template 新特性
自C++11起,function template 可拥有默认的 template 实参。此外,local type 可被当作template 实参。