1

I am currently new to C++ in the working world (learnt C++ academically). This is my first job where C++ is the base requirement.

May I ask -

  1. When do I use a template for a class?
  2. Is there any ideal or good practices that uses a template in a derived class, where the base class does not inherit any templates?

For example:

class Base {};

<typename T>
class Derived : public Base {};

The reason why I need to inherit from a base is because I need to store objects where it can be referenced from the base, and thereafter have a common factory method where I can pull information out.

Benny Ng
  • 13
  • 3
  • What do you need the template for? – Retired Ninja Dec 15 '21 at 06:54
  • Yes it can be a totally valid design, specialy if you want a collection of Base instances (e.g. in a vector). I use it a lot, though mostly I only let Base be an abstract base class (interface) without putting logic in it. – Pepijn Kramer Dec 15 '21 at 07:10
  • 1
    Basically, you are asking one single question: when do we use template. In a word, use template when you have to regard a type as a changeable stuff. – Yves Dec 15 '21 at 07:18
  • 1
    Yes, it is a good practice in some cases. A typical use case is _type erasure_. See, e.g., https://stackoverflow.com/a/34815953/580083. Another one may be _CRTP_ with a single common base, such as shown here: https://katyscode.wordpress.com/2013/08/22/c-polymorphic-cloning-and-the-crtp-curiously-recurring-template-pattern/. – Daniel Langr Dec 15 '21 at 08:09
  • 1
    A non-templated base can be useful for collecting members that don't depend on T. This way all `Derived`s can use the common code. – BoP Dec 15 '21 at 09:53

0 Answers0