简体   繁体   English

C ++中的模板中的typename

[英]typename in Templates in C++

What is the difference between following two usages of templates? 以下两个模板用法有什么区别?

Usage 1: 用法1:

template<class T> class U : A<T>
{
  T::B x;
  void f(A<T>& y) { *y++; }
};

Usage 2: 用法2:

template<class T> class U : A<T>
{
  typename T::B x;
  void f(A<T>& y) { *y++; }
};

Is there any ambiguity in 1? 1中有歧义吗?

The difference is that "Usage 1" should not compile. 不同之处在于“用法1”不应编译。 When a dependent name like T::B is not preceded by typename , it is assumed to refer to an object or function member. 当像T::B这样的从属名称前面没有typename ,假定它引用一个对象或函数成员。 In which case, T::B x; 在这种情况下, T::B x; is invalid syntax. 是无效的语法。

According to the standard, $14.6/2 Name resolution [temp.res] 根据标准,$ 14.6 / 2名称解析[temp.res]

A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename. 假定模板声明或定义中使用的名称以及依赖于模板参数的名称不会命名类型,除非适用的名称查找找到类型名称或名称由关键字typename限定。

That means, if you don't use the keyword typename for T::B x; 这意味着,如果你不使用T::B x;的关键字typename T::B x; , T::B will be considered as a non-type name, such as a member B of T , whick makes T::B x; T::B将被视为非类型名称,例如T的成员B ,whick使T::B x; ill-formed. 病态的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM