首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Templates

模板是定义下列之一的C++实体:

  • A类家庭%28类模板%29,这可能是嵌套类
  • a函数族%28功能模板%29,这可能是成员函数
  • 类型为%28的家族的别名别名模板%29%28自C++11%29
  • 变量族%28可变模板%29%28自C++14%29

模板由一个或多个参数化。模板参数,分为三类:类型模板参数、非类型模板参数和模板参数.

当提供模板参数时,或者功能和类%28由于仅推导出C++17%29模板,因此它们被替换为模板参数以获得专业化的模板,即特定类型或特定函数lvalue。还可以明确规定专门化:完全专业化类模板和函数模板都允许,部分专业化只允许使用类模板。

当类模板专门化在需要完整对象类型的上下文中被引用时,或者当函数模板专门化在需要函数定义才能存在的上下文中被引用时,模板是实例化%28它的代码实际上编译为%29,除非模板已经显式地专门化或显式实例化。类模板的实例化不会实例化它的任何成员函数,除非它们也被使用。在链接时,合并由不同的翻译单元生成的相同的实例化。

模板的定义必须在隐式实例化点上可见,这就是为什么模板库通常在Header%28(例如)中提供所有模板定义的原因。大多数Boost库都是只包含头的。29%。

句法

template < parameter-list > declaration

(1)

?

export template < parameter-list > declaration

(2)

(until C++11)

declaration

-

declaration of a class (including struct and union), a member class or member enumeration type, a function or member function, a static data member at namespace scope, a variable or static data member at class scope, (since C++14) or an alias template (since C++11) It may also define a template specialization.

parameter-list

-

a non-empty comma-separated list of the template parameters, each of which is either non-type parameter, a type parameter, a template parameter, or a parameter pack of any of those.

export was an optional modifier which declared the template as exported (when used with a class template, it declared all of its members exported as well). Files that instantiated exported templates did not need to include their definitions: the declaration was sufficient. Implementations of export were rare and disagreed with each other on details.

(until C++11)

模板实体

除了类/函数/变量模板本身之外,模板中定义的各种实体从来不被认为是可以单独实例化%28的实体,这反过来包括这些实体的默认参数、异常规范、非静态数据成员初始化器等。因此,这些非模板实体进行模板实例化:查找相关名称,检查语义约束,并将所使用的任何模板实例化为声明该实体的模板的实例化的一部分。与模板一起,这些实体被称为“模板实体”%28,或者在某些源中称为“tEmploid”%29。

所有下列实体都是模板实体:

  • 类/函数/变量模板
  • 模板实体%28的成员,例如类模板%29的非模板成员函数。
  • 枚举的枚举数,它是一个模板实体。
  • 在模板实体中定义或创建的任何实体:本地类、局部变量、朋友函数等。
  • 出现在模板实体声明中的lambda表达式的闭包类型。
代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com