Can I override and subclass the template type as a superclass
Can I override and subclass the template type as a superclass.
I am a Java programmer and this works well with generics, but I am not familiar with how much to do in C ++
Can I use the class
template <typename T>
class A{
public:
T get(){
return t;
}
A(){
}
void set(T tt){
t=tt;
}
private:
T t;
};
And expand it with something like
class B:A<B>
Where subclass B is used as a generic type for class A and no generics are required for class B
source to share
Basically, the use of templates is called Curiously Repeating Template Pattern (CRTP) and is perfectly correct.
However, keep in mind that Java templates and C ++ templates are very different at very many points, including the restrictions on the use of B in A. Derived CRTP classes are incomplete when instantiating the template, so you cannot allocate any objects of them in the base class like you. This is why your code won't compile . The usual method is to use accessor methods like:
void set(T tt){
static_cast<T&>(*this)=tt;
}
source to share