In the following code, I have a templated class, that derives from another templated class.
For the code to be valid, I found that every reference to a base class member from the derived class needed to be fully specified (with
thingbase<T>::
. That seems redundant. Moreover, members accessed with
this->
are exceptions; they don't need any specification of the parent class, which appears inconsistent.
Naturally, members accessed from the main code also don't need the full specification. It is expected, but it only makes me wonder even more about the need for the full specification from within the class.
I assume there is a very good reason related to the mechanics of template resolution, but I fail to grasp it. Can someone explain?
I came to this because I am writing a family of classes with multiple template specializations and I realized that I kept repeating some common elements; in particularly complicated typedef derived from a template argument, I was hoping to find a way to avoid these repetitions. One way is to use template specialization of functions and variables from with one single class definition, but then one needs to keep repeating the same template selectors, and the code becomes even messier. Any suggestion?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <iostream>
#include <vector>
template<class T>
class thingbase{
public:
typedef typename std::vector<T> vec;
T c;
thingbase(T x):c(x){}
};
template<class T>
class thing:public thingbase<T>{
public:
thing(T x):thingbase<T>::thingbase(x){
std::cout << this->c << std::endl; // Why is this OK but ..
std::cout << thingbase<T>::c << std::endl; // specifying thingbase<T>:: is required here ?
}
typename thingbase<T>::vec makevec(){return typename thingbase<T>::vec({thingbase<T>::c});} // and here !
};
int main ()
{
auto t =thing<int>(7);
auto vt = t.makevec();
for(auto i:vt){std::cout << i << std::endl;}
std::cout << t.c << std::endl;
}
|