Why `this` is a type-dependent expression even if the template class has no base class?
可以编译以下代码而不出错:
1 2 3 4 5 6 | template <typename T> struct A { void f() { this->whatever; } // whatever is not declared before }; int main() { A<int> a; } |
我知道这是因为
我可以理解,如果类模板有一个依赖于类型的基,那么
1 2 3 4 5 6 7 | template <typename T> struct B { T whatever; }; template <typename T> struct A : B<T> { void f() { this->whatever; } }; int main() { A<int> a; } |
在解析模板类
那么,在第一个例子中,
您的代码"格式不正确,不需要诊断",因为
然而,仅仅因为
A class member access expression ([expr.ref]) is type-dependent if the expression refers to a member of the current instantiation and the type of the referenced member is dependent, or the class member access expression refers to a member of an unknown specialization.
这是有关从属名称的名称查找规则。
$14.6/9名称解析[温度]:
When looking for the declaration of a name used in a template definition, the usual lookup rules ([basic.lookup.unqual], [basic.lookup.argdep]) are used for non-dependent names. The lookup of names dependent on the template parameters is postponed until the actual template argument is known ([temp.dep]).
其目的是,如果名称依赖于模板参数,则信息不足,直到知道实际的模板参数为止。编译器不会区分依赖名称的类型(由
您的示例可以进一步简化:
1 2 3 4 5 6 | template <typename T> struct A { void f() { this = 1; } }; int main() { A<int> a; } |
声明
正如JohannesSchaub-Litb已经回答的那样,这可能是一种"不需要诊断"的情况。