《C++11标准库》3.1.9崭新的 Template 特性与Alias Template

自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 实参。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值