Reputation: 1407
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
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
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