C++ 模板类型参数

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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值