有模板实例化(“两阶段名称查找”)两个阶段。
在第一阶段,所有非从属名称都被解析(查找)。在第二阶段,依赖名称被解析。
一个从属名称是依赖于模板参数的名称,例如:
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
这正是我所描述。在好的术语中,在阶段2, 中查找t
,因为this
取决于模板参数。
错误的术语在阶段1中查找,因为该名称中的任何内容都不依赖于模板参数。 但是在相1中,没有a
是可见的,因为编译器不能在阶段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我甚低频博客。
Joachim Pileborg给你答案。除此之外,所提供的代码还有其他一些问题妨碍了它的编译。 – Anonymous 2012-04-16 09:07:44
这是实际的码?在类定义之后没有后缀分号,而int B:f()'的作用域运算符不正确,并且在错误行处没有分号。 –
hmjd
2012-04-16 09:07:53
哦,这只是一个打字错误。我修好了它。 – 2012-04-16 09:17:07