Is a base base class legal?

This seems to work, but I'm not 100% sure that it is legal, and I would appreciate some of the reviews.

I have a subclass that is derived from a base base class. It looks like a curiously repeating pattern template, but different.

Derived .h:

template <class T> class Derived : public T { public: Derived(); ... and some other stuff ... }; 

In the output.cpp file:

 #include "derived.h" template <class T> Derived<T>::Derived() { ... } // defining the variations I need here avoids linker errors // see http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13 template Derived<Base1>::Derived(); template Derived<Base2>::Derived(); 

And in another file:

 #include "derived.h" void test() { Derived<Base1> d1; Derived<Base2> d2; ... do stuff with d1 and d2 ... } 
+4
source share
2 answers

Yes, you can get any class, including one that (or depends on) the template argument.

As noted in the comments, it must be a full type; that is, it must be defined before the template is instantiated.

+5
source

In C ++ there is no such thing as a "common class". You have a template , and the template is not a class. Rather, template instances become classes. However, these are completely different, separate, and unrelated classes, so Derived<A> and Derived<B> have nothing to do with each other.

In addition, what you do is beautiful. In any instance of the Derived<T> template, T is the actual class (suppose it is actually a class, not, say, an array or int ), and you can extract from it.

+5
source

Source: https://habr.com/ru/post/1396907/


All Articles