啊啊
template <typename T>
class A
{
public:
int a;
}
b.h
template <typename T>
class B : public A<T>
{
public:
int f();
}
template <typename T>
int B<T>::f()
{
int t;
t = this->a; //Okay
t = a //Error
return 0;
}
为什么不使用this->
会出错?
我可以使用某种方法省略 this->
吗?
(我修正了一些错误)
最佳答案
模板实例化有两个阶段(“两阶段名称查找”)。
在第一阶段,解析(查找)所有非依赖名称。在第二阶段,解析依赖名称。
依赖名称是依赖于模板参数的名称,例如:
template <typename T>
void foo() {
x = 0; // <- Non-dependent, nothing in that refers to "T".
// Thus looked up in phase 1, therefore, an 'x' must be
// visible.
T::x = 0; // <- Dependent, because it depends on "T".
// Looked up in phase 2, which is when it must be visible.
}
现在,你写:
t = this->a; //Okay
t = a //Error
这正是我所描述的。在好的术语中,t
在第 2 阶段被查找,
因为 this
取决于模板参数。
在第 1 阶段查找错误的术语,因为该名称中的任何内容都不依赖于模板参数。
但是在阶段 1 中,没有 a
是可见的,因为编译器无法内省(introspection)基类模板
在第 1 阶段,因为模板可以专门化并且在实例化时,
它可以远离主模板声明,另一个特化
没有a
,可能是可见的。
例子:
template <typename T>
struct Base {
};
template <typename T>
struct Derived : Base<T> {
void foo() {
this->a = 0; // As is valid. `this->a` is looked up in phase 2.
}
};
template <> struct Base<int> {
int a;
};
int main ()
{
// The following declarations trigger phase 2 lookup.
Derived<int> di; // valid, because a later specialized
// Base<int> is used and all symbols
// are resolved.
Derived<float> df; // not valid
}
顺便说一句,我曾经写过 this-> is not only a matter of style 在我的频率非常低的博客中。
关于c++ - 为什么我不能使用作为模板类的父类的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10171242/