【问题标题】:problem with template inheritance模板继承问题
【发布时间】:2010-06-06 00:28:47
【问题描述】:

我试图了解为什么我在此代码中收到错误: (错误在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 T& B::get() 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::”是没有意义的……

【问题讨论】:

    标签: c++ inheritance templates


    【解决方案1】:

    您也可以使用this-&gt;t 访问基类模板成员。

    B::get()中,名称t不依赖于模板参数T,因此不是依赖名称。基类A&lt;T&gt; 显然依赖于模板参数T,因此是一个依赖基类。不依赖的名称不在依赖的基类中查找。 A detailed description of why this is the case can be found in the C++ FAQ Lite.

    【讨论】:

    • FAQ 关于“this->”起作用的原因是错误的。将其与标准进行比较(由我强调)。常见问题解答:“由于 this 在模板中总是隐式依赖,因此 this->f 是依赖的,因此查找被推迟直到模板被实际实例化,此时会考虑所有基类 ", Standard: "...在非限定名称查找期间,无论是在类模板或成员的定义点还是在实例化期间不检查基类范围 /i> 的类模板或成员。”。常见问题解答说找到它是因为它是依赖的,但这是错误的。
    • GCC 也实现了这个错误的解释,结果has bug reports open
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多