gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:08:03 25 4
gpt4 key购买 nike

此代码使用 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;
}
};

更换 data this->data Derived::getdata()让 Clang 开心。

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

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

最佳答案

叮当是对的。

$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/63219699/

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