本文共 1465 字,大约阅读时间需要 4 分钟。
16.1.4. Template Type Parameters
Distinction Between typenameand class
In a function template parameter list, the keywords typenameand classhave the same meaning and can be used interchangeably.
Designating Types inside the Template Definition
In addition to defining data or function members, a class may define type members. For example, the library container classes define various types, such as size_type, that allow us to use the containers in a machine-independent way. When we want to use such types inside a function template, we must tell the compiler that the name we are using refers to a type.
We must be explicit because the compiler (and a reader of our program) cannot tell by inspection when a name defined by a type parameter is a type or a value. As an example, consider the following function:
template <class Parm, class U> Parm fcn(Parm* array, U value) { Parm: :size_type * p; // If Parm::size_type is a type, then a declaration // If Parm::size_type is an object, then multiplication }
We know that size_typemust be a member of the type bound to Parm, but we do not know whether size_typeis the name of a type or a data member. By default, the compiler assumes that such names name data members, not types.
If we want the compiler to treat size_typeas a type, then we must explicitly tell the compiler to do so:
template <class Parm, class U> Parm fcn(Parm* array, U value) { typename Parm::size_type * p; // ok: declares p to be a pointer }
转载地址:http://zfyii.baihongyu.com/