模板继承的问题 [英] problem with template inheritance

查看:81
本文介绍了模板继承的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解我在这段代码上遇到错误:
(错误在g ++ unix编译器下.VS编译正常)

I'm trying to understand whay i get an error on this code: (the error is under g++ unix compiler. VS is compiling OK)

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'未在此范围内声明

main.cpp: In member function 'const T& B::get() const':
main.cpp:23: error: 't' was not declared in this scope

它确实当我将B的代码改为此时编译:

It did compiled when i changed the code of B to this:

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 ::是没有意义的......

I just cant understand what is the problem with the first code...
It doesn't make sense that i really need to write "A::" every time...

推荐答案

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

You can also use this->t to access the base class template member.

中B :: get(),名称 t 不依赖于模板参数 T ,所以它不是一个从属名称。基类 A< T> 显然取决于模板参数 T ,因此是依赖基类。在从属基类中不查找非依赖名称。 有关原因的详细说明,请参阅C ++ FAQ Lite

In B::get(), the name t is not dependent on the template parameter T, so it is not a dependent name. Base class A<T> is obviously dependent on the template parameter T and is thus a dependent base class. Nondependent names are not looked up in dependent base classes. A detailed description of why this is the case can be found in the C++ FAQ Lite.

这篇关于模板继承的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆