Search code examples
c++templatesinheritanceradixderived

C++: Can I write a template class that derives from T?


I'm not exactly sure how to word this in English, but I want to do something like this:

template <class T>
class derived: public T
{ blah };

Where basically, I have a template class, but I'm deriving a new class from the class that is specified in the template? I.e. so I wouldn't necessarily know the class at compile time.

Is this even possible?
If so, What are the semantics for this?

For example, say I'm trying to write a "parent" class. For the purposes of this example, let's say it's a tree parent. The tree parent, is a tree itself (so it inherits from tree), but also has a vector of references to child trees.
However, the parent class itself doesn't have to be a tree; it could be any class, such that I could write something like:

Parent<tree> treeParent;
Parent<shrub> shrubParent;

Solution

  • Yes. That is possible. Try doing that.

    I wouldn't necessarily know the class at compile time.

    I think, you mean "I wouldn't necessarily know the class at the time of defining the class template."

    By the time you compile, you've already defined the class template, and used it in your code, passing template argument to it, which means you know the class (i.e template argument) at compile time. If you don't know the class to be used as base, then you cannot even compile the code.