rxu
rxu

Reputation: 1407

Access attribute of template base class without "using"

I want to use an attribute defined in the template base class A in a method of template derived class B.
So far, I found using works.
But writing a using statement for every single attribute of A is tedious.
How to avoid writing so many using statements?

#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();
}

Upvotes: 2

Views: 77

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

// how to get rid of this?

You can write

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

or

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

to get rid of the using statement.

Upvotes: 2

Guillaume Racicot
Guillaume Racicot

Reputation: 41760

Because you are extending a class that is dependent of a template parameter, this become a dependent name. You must use this explicitly:

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

Or you can even specify the class name:

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

The third solution is, of course, the using statement.

Upvotes: 4

Related Questions