c++ - 允许 `this->` 访问依赖基类的成员的规则是什么?

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

我们知道,下面的代码格式不正确,因为成员 x 在依赖的基类中。但是,将指定行上的 x 更改为 this->x 将修复错误。

template <typename T>
struct B {
    int x;
};
template <typename T>
struct C : B<T> {
    void f() {
        int y = x; // Error!
    }
};
int main() {
    C<int> c;
    c.f();
}

我想解释一下标准中如何指定此行为。根据[temp.dep]/3:

In the definition of a class or class template, if a base class depends on a template-parameter, the base class scope 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.

这似乎解释了为什么单独使用 x 会失败。名称 x 在定义点查找,并且不检查基类范围。但是,如果我们使用 this->x 会怎样?现在名称 x 是依赖的,它的查找被推迟到实例化。但是引用的段落似乎暗示 即使在实例化时也不应该找到 x 因为在 this- 中查找 x >x 仍然是 不合格查找。

显然,实现的行为不是这样的,而且人们普遍认为,一旦模板被实例化,就会搜索基类范围

  1. 我是否误解了引用的段落?
  2. 是否有指定“正确”行为的段落?

最佳答案

类成员访问表达式 (5.2.5. [expr.ref]) 不使用非限定查找规则,它们使用类成员访问查找规则 (3.4.5 [basic.lookup.classref])。

(2) If the id-expression in a class member access (5.2.5) is an unqualified-id, and the type of the object expression is of a class type C, the unqualified-id is looked up in the scope of class C.

关于c++ - 允许 `this->` 访问依赖基类的成员的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32665178/

相关文章:

c++ - midifile : getDurationInSeconds is 0 for all events

c++ - 在 C++ 中基于大小的运行时类型转换

c++ - 允许使用 char* 别名 T*。反过来也允许吗?

Javascript 多行字符串和意外 token ILLEGAL

c++ - 有没有办法在 std::conditional fail 上给出更好的错误?

c++ - 将 std::string 的 c_str() 结果分配给标准保证安全的同一个 std::string?

c++ - 对于按值传递的重成员,构造函数的初始化列表中真的需要 std::move 吗?

c++ - 跳转到 C++ 第 5 章问题 7

c++ - 找到系统的行终止符

c++ - C++中的指针容器