c++ - this-> 是否必须从派生类访问 Base<T> 标识符?

标签 c++ templates inheritance language-lawyer name-lookup

此代码使用 MSVC 2015 编译,但不能使用 Clang 5.0.0(主干 304874)编译:

template <typename T>
struct Base
{
  T data;
};

template <typename T>
struct Derived : Base<T>
{
  auto getData() const
  {
    return data;
  }
};

Derived::getdata() 中将 data 替换为 this->data 让 Clang 很高兴。

根据 C++ 标准,哪个编译器是正确的?

必须在模板代码中使用 this-> 来访问基类的标识符吗?

最佳答案

Clang 是正确的。

$17.6.2/3 Dependent names [temp.dep]

In the definition of a class or class template, the scope of a dependent base class is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.

对于 return data; , data 不合格,则将采用不合格名称查找。这意味着基类中的名称Base<T> (这是一个依赖基类,因为它依赖于模板参数 T )不应该被发现;即不依赖的名称不在依赖的基类中查找。

this->dataBase<T>::data使其合格。这意味着将在实例化时查找名称,届时将知道必须探索的确切基础特化。

关于c++ - this-> 是否必须从派生类访问 Base<T> 标识符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44416954/

相关文章:

c++ - 未从 main.cpp C++ 调用 C 函数

c++ - 将旧指针数组的元素复制到新指针数组中?

c++ - 在 metatrader4 中创建一个基本的 dll

java - 协变返回或泛型

jpa - Kotlin 继承和 JPA

避免指针比较的 C++ 技巧

c++ - 显式特化是使用部分特化语法

javascript - 适用于客户端和服务器的 ASP.NET MVC 模板

c++ - 不调用部分专用模板类(用于容器类类型)

java - 为什么我不能直接在子类中使用可重入类的 getOwner() 方法?