2010-06-06 106 views
5

我想了解whay我在此代码得到一个错误: (是在G ++ UNIX编译器错误VS正在编制确定。)问题模板继承

template<class T> class A { 
public: 
    T t; 
public: 
    A(const T& t1) : t(t1) {} 
    virtual void Print() const { cout<<*this<<endl;} 
    friend ostream& operator<<(ostream& out, const A<T>& a) { 
      out<<"I'm "<<typeid(a).name()<<endl; 
      out<<"I hold "<<typeid(a.t).name()<<endl; 
      out<<"The inner value is: "<<a.t<<endl; 
      return out; 
    } 
}; 

template<class T> class B : public A<T> { 
public: 
    B(const T& t1) : A<T>(t1) {} 
    const T& get() const { return t; } 
}; 

int main() { 
    A<int> a(9); 
    a.Print(); 
    B<A<int> > b(a); 
    b.Print(); 
    (b.get()).Print(); 
    return 0; 
} 

此代码是给下面的错误:

main.cpp中:在成员函数 'const的Ť& B ::得到()const的':
main.cpp中:23:错误: 'T' 在此范围内未声明

它当我编译时改变B的这个代码:

template<class T> class B : public A<T> { 
public: 
    B(const T& t1) : A<T>(t1) {} 
    const T& get() const { return A<T>::t; } 
}; 

我只是无法理解什么是第一个代码问题...
它没有任何意义,我真的需要写“A ::”每时间...

回答

7

您还可以使用this->t来访问基类模板成员。

B::get()中,名称t不依赖于模板参数T,所以它不是依赖名称。基类A<T>显然依赖于模板参数T,因此是一个从属基类。非依赖名称不在相关的基类中查找。 A detailed description of why this is the case can be found in the C++ FAQ Lite

+2

关于“this->”原因的常见问题解答是错误的。将其与标准进行比较(由我强调)。 FAQ:“由于这总是隐式地依赖于模板,因此this-> f *是相关的,因此查找会延迟*直到模板实际实例化,此时所有基类都被视为*”,Standard:“。 ..在类模板或成员的定义点或者在类模板或成员的实例化过程中,在非限定名称查找过程中,基类范围*不会被检查。“常见问题解答表示找到它是因为它是依赖的,但这是错误的。 – 2010-06-06 00:49:33

+1

GCC也实现了这个错误的解释,并因此[有错误报告打开](http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43282) – 2010-06-06 00:56:22