Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a Generic Base Class Legal?

This seems to work, but I'm not 100% certain it's legal and would appreciate some feedback.

I have a subclass that is derived from a generic base class. It's similar to the curiously recurring template pattern, but different.

In derived.h:

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

In derived.cpp:

#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 some other file:

#include "derived.h"

void test()
{
    Derived<Base1> d1;
    Derived<Base2> d2;
    ... do stuff with d1 and d2 ...
}
like image 752
criddell Avatar asked Dec 28 '22 05:12

criddell


1 Answers

Yes, you can derive from any class, including one that is (or is dependent on) a template argument.

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

like image 57
Mike Seymour Avatar answered Dec 29 '22 18:12

Mike Seymour