rxu rxu - 3 months ago 12
C++ Question

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?

Thanks.

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

Answer

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.

Comments