gpt4 book ai didi

c++ - 模板的模板成员的消歧模板关键字 : when exactly?

转载 作者:太空狗 更新时间:2023-10-29 23:47:16 27 4
gpt4 key购买 nike

这里给出了一个关于模板消歧器的问题:

template disambiguator

在答案中我们可以读到:

ISO C++03 14.2/4

When the name of a member template specialization appears after . or -> in a postfix-expression, or after nested-name-specifier in a qualified-id, and the postfix-expression or qualified-id explicitly depends on a template-parameter (14.6.2), the member template name must be prefixed by the keyword template. Otherwise the name is assumed to name a non-template.

下面是我不太明白的具体例子:

template <class T>
class Base {
public:


template <int v>
static int baseGet() {return v;}

class InnerA {
public:

template <int v>
static int aget() {return v;}

};

class InnerB {
public:
typedef Base BaseType;
typedef BaseType::InnerA OtherType;

template <int v>
static int baseGet() {return BaseType::baseGet<v>();} //(A)

template <int v>
static int aget() {return OtherType::aget<v>();} //(B)
};
};

显然编译失败。你需要template在 (B) 行中:OtherType::template aget<v>(); .但是,g++ (4.4.3) 和 clang++ (2.9) 都不会提示缺少 template。在 (A) 行中。为什么? BaseType取决于类型 T ,不是吗?是那些编译器偏离了标准,还是我误解了标准中的某些内容?

最佳答案

它们实现了 C++0x 规范,其中 Base当前实例化。而 C++0x 允许省略 template在这种情况下的关键字。自 BaseTypeBase 的类型定义,当你说 BaseType ,它也命名了当前的实例化。

引用规范,因为你似乎对规范引用感兴趣

A name is a member of the current instantiation if it is [...]

  • A qualified-id in which the nested-name-specifier refers to the current instantiation and that, when looked up, refers to at least one member of the current instantiation or a non-dependent base class thereof.

A name refers to the current instantiation if it is [...]

  • in the definition of a [...] nested class of a class template, [...], the injected-class-name (Clause 9) of the class template or nested class

和(您引用的修改后的 14.2/4)

[...] or the nested-name-specifier in the qualified-id refers to a dependent type, but the name is not a member of the current instantiation (14.6.2.1), the member template name must be prefixed by the keyword template. [...]


注意:在 C++03 中,您的代码格式错误,因为 BaseTypeOtherType是依赖的。规范说:

A type is dependent if it is [...]

  • a template parameter
  • a qualified-id with a nested-name-specifier which contains a class-name that names a dependent type
  • a template-id in which either the template name is a template parameter or any of the template arguments is a dependent type

(注意 Base 等同于 Base<T> ,它是 BaseBaseType::InnerA 是依赖类型的基础)。

请注意,您引用中的“明确依赖”是一个准标准术语,最近才被删除(我相信是在 1996 年 12 月)。它基本上意味着(在这种情况下)限定符依赖的限定 ID 或类成员访问( a->x/a.x ),其中 a是依赖的。 “explicitly depends”从草案中删除后,它仍然潜伏在某些地方,甚至 C++0x 在 14.6.2p2 的注释中仍然提到“explicitly depends”:

the base class name B<T>, the type name T::A, the names B<T>::i and pb->j explicitly depend on the template-parameter.

关于c++ - 模板的模板成员的消歧模板关键字 : when exactly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6456636/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com