2.11 Summary

2.11 小结

 

  • A class template is a class that is implemented with one or more type parameters left open.

   类模板是具有如下性质的类:在类的实现中,可以有一个或多个类型参数还没有被指定。

  • To use a class template, you pass the open types as template arguments. The class template is then instantiated (and compiled) for these types.

   为了使用类模板,你可以传入那些还未指定的类型作为模板的实参;然后编译器将基于该类型来实例化类模板。

  • For class templates, only those member functions that are called are instantiated.

   对于类模板而言,只有那些被调用的成员函数才会被实例化。

  • You can specialize class templates for certain types.

  可以用某种特定类型特化类模板。

  • You can partially specialize class templates for certain types.

  可以用某种特定类型局部特化类模板。

  • Since C++17, class template arguments can automatically be deduced from constructors.

  从C++17开始,类模板实参可以从构造函数中自动推导出来。

  • You can define aggregate class templates.

  可以定义一个聚合类模板

  • Call parameters of a template type decay if declared to be called by value.

  当声明按值传递参数时,模板类型的形参类型会发生退化(decay)。

  • Templates can only be declared and defined in global/namespace scope or inside class declarations.

  只能在全局/名称空间作用域或类声明内部声明和定义模板。

 

1. C++17 introduced class argument template deduction, which allows skipping template arguments if they can be derived from the constructor. This will be discussed in Section 2.9 on page 40.

1. C++17引入了类模板实参的推导,如果他们可以从构造函数中推断出来的话,就允许略过模板实参。这将在第40页的2.9节中加以讨论。

 

2. It is a templated entity, see Section 12.1 on page 181.

2. 它是一个模板化的实体,请参阅181页的12.1节。

 

3. Using the word typedef instead of “type definition” in intentional. The keyword typedef was originally meant to suggest “type definition.” However, in C++,“type definition” really means something else (e.g., the definition of a class or enumeration type). Instead, a typedef should just be thought of as an alternative name (an “alias”) for an existing type, which can be done by a typedef.

3. 有意使用单词typedef而不是“类型定义”。关键字typedef最初是建议“类型定义”。但是,在C++中“类型定义”实际上表示其他的含义(例如,类或枚举类型的定义)。相反,应该将typedef视为现有类型的替代名称(“别名”),这可以由typedef来定义。

 

4. Alias templates are sometimes (incorrectly) referred to as typedef templates because they fulfill the same role that a typedef would if it could be made into a template.

4.别名模板有时(不正确地)称为typedef模板。因为他们所扮演的角色与typedef(如果可以将其生成模板)所扮演的角色相同。

 

5. The typename is necessary here because the member is a type. See Section 5.1 on page 67 for details.

5. 如果类成员是个类型的话,那么就必须加typename(更多详细信息,请参阅67页5.1节)。

 

6. Even worse, there is a vector constructor taking one integral argument as initial size, so that for a stack with the initial value 5, the vector would get an initial size of five elements when : elems(elem) is used.

6. 更糟糕的是,vector有个带一个整型参数的构造函数,该参数用于初始化vector的大小。因此,对于初始值为5的栈,当使用elems(elem)时,将会得到一个含有5个元素大小的vector。