template<class T>
struct A {
T i;
};
template<class T>
struct B : A<T> {
T foo() {
return this->i; //standard accepted by all compilers
//return i; //clang and gcc will fail
//clang 13.1.6: use of undeclared identifier 'i'
//gcc 11.3.0: 'i' was not declared in this scope
//Microsoft C++ Compiler 2019 will accept it
}
};
int main() {
B<int> b;
b.foo();
}
如果省略 this-> ,一些编译器不知道如何处理 i 。 In order to tell it that i is indeed a member of A<T> , for any T , the this-> prefix is required.
注意:仍然可以使用以下命令省略 this-> 前缀:
template<class T>
struct B : A<T> {
int foo() {
return A<T>::i; // explicitly refer to a variable in the base class
//where 'i' is now known to exist
}
};
通常,您不必这样做,暗示
this->
。有时,存在名称歧义,可用于消除类成员和局部变量的歧义。但是,这是一个完全不同的情况,其中明确需要
this->
。考虑以下代码:
如果省略
this->
,一些编译器不知道如何处理i
。 In order to tell it thati
is indeed a member ofA<T>
, for anyT
, thethis->
prefix is required.注意:仍然可以使用以下命令省略
this->
前缀: