栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

自C++11起,template 可以拥有那种“得以接受个数不定之 template 实参”的参数。此能力称为 variadic template (可变参数宏)。例如,对于print()函数,得以在调用它时给予不定个数的实参且各具不同类型:

void print()
{
	std::cout << "执行无参print()" << std::endl;
}
template
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
using Vec = std::vector>;
 Vec coll;
等价于
 std::vector> coll;

其他的 Template 新特性

自C++11起,function template 可拥有默认的 template 实参。此外,local type 可被当作template 实参。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/836580.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号