没有“使用”的模板基类的访问属性

时间:2016-09-01 17:53:17

标签: c++ templates inheritance

我想在模板派生类A的方法中使用模板基类B中定义的属性。
到目前为止,我发现using有效 但是为using的每个属性编写A语句都很繁琐 如何避免编写这么多using语句?

#include <iostream>

using namespace std;

template <typename T>
class A{
    public:
        A(){
            a = 10;
        }
        //virtual destructor
        virtual ~A(){
            cout << "~A() is called" << endl;
        }
    protected:
        T a;
} ;

template <typename T>
class B : public A<T>{
    public:
        void f(void){
            cout << a << endl;
        }
        virtual ~B(){
            cout << "~B() is called" << endl;
        }
    private:
        using A<T>::a; //how to get rid of this?
} ;

int main(void){
    B<int> bb;
    bb.f();
}

2 个答案:

答案 0 :(得分:4)

因为您正在扩展依赖于模板参数的类,所以this将成为依赖名称。您必须明确使用this

template <typename T>
struct B : A<T>{
    void f(){
        std::cout << this->a << std::endl;
    }
};

或者您甚至可以指定班级名称:

template <typename T>
struct B : A<T>{
    void f(){
        std::cout << A<T>::a << std::endl;
    }
};

第三种解决方案当然是using声明。

答案 1 :(得分:2)

// how to get rid of this?

你可以写

    void f(void){
        cout << A<T>::a << endl;
    }

    void f(void){
        cout << this->a << endl;
    }

删除using语句。

相关问题