Template and inheritance

Solved
jihane jihane Posted messages 100 Status Membre -  
jihane jihane Posted messages 100 Status Membre -
Hello,

Please, can a derived class use the generic type of the base class if the base class is declared as a template
template<class T> NAME OF THE CLASS? In other words, can we use the keyword T instead of the type in the derived class? Thank you for your forthcoming reply :)

1 réponse

KX Posted messages 19031 Status Modérateur 3 020
 
Every time you replace your template with a concrete type, you compile a new class, which in turn will compile its parent class. In the end, you will only have concrete types. So there shouldn't be any problem...

template <typename T> class Parent { } template <typename T> class Child : public Parent<T> { }

--
Trust does not exclude control.
0
jihane jihane Posted messages 100 Status Membre
 
So we can say that the child class inherits the abstract type??? And thank you for the answer.
0
KX Posted messages 19031 Status Modérateur 3 020
 
It is only abstract in your code; once the compilation is done, the class is concrete, and there is no more ambiguity than if you had created multiple parent classes and multiple child classes with only the template type differing.
0
jihane jihane Posted messages 100 Status Membre
 
OK thanks, but if I want to declare the child class as being generic but with a different type, that is to say not the one from the parent class, what would I do??
0
KX Posted messages 19031 Status Modérateur 3 020
 
You would act as if the parent class was not a template...

I am not sure about the syntax with two templates, but in principle, these two codes should have roughly the same meaning for the child class.

class Parent {} template <typename T> class Child : public Parent {} //------------ template <typename U> class Parent {} template <typename T,typename U> class Child : public Parent<U> {}
0
jihane jihane Posted messages 100 Status Membre
 
Thank you very much for helping me, and thank you for your time now I understand well :)
0