Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use template vs inheritance

I've been looking around for this one, and the common response to this seems to be along the lines of "they are unrelated, and one can't be substituted for the other". But say you're in an interview and get asked "When would you use a template instead of inheritance and vice versa?"

like image 597
Brent212 Avatar asked Aug 31 '11 22:08

Brent212


People also ask

Is inheritance better than templates?

Templates provide sortability in a much nicer way, since the sortee doesn't need to know that it's being sorted. Complex inheritance typically results when you work with a forced mindset that everything must be an inheritance hierarchy, which is in fact rarely appropriate.

When should I use a template C++?

Templates are very useful when implementing generic constructs like vectors, stacks, lists, queues which can be used with any arbitrary type. C++ templates provide a way to re-use source code as opposed to inheritance and composition which provide a way to re-use object code.

What is the main advantage of using template functions?

Advantages. C++ templates enable you to define a family of functions or classes that can operate on different types of information. Use templates in situations that result in duplication of the same code for multiple types.

Can template class be inherited?

Inheriting from a template class is feasible. All regular inheritance and polymorphism rules apply. If we need the new derived class to be general, we must make it a template class with a template argument sent to the base class.


1 Answers

The way I see it is that templates and inheritance are literally orthogonal concepts: Inheritance is "vertical" and goes down, from the abstract to the more and more concrete. A shape, a triange, an equilateral triangle.

Templates on the other hand are "horizontal" and define parallel instances of code that knowns nothing of each other. Sorting integers is formally the same as sorting doubles and sorting strings, but those are three entirely different functions. They all "look" the same from afar, but they have nothing to do with each other.

Inheritance provides runtime abstraction. Templates are code generation tools.

Because the concepts are orthogonal, they may happily be used together to work towards a common goal. My favourite example of this is type erasure, in which the type-erasing container contains a virtual base pointer to an implementation class, but there are arbitrarily many concrete implementations that are generated by a template derived class. Template code generation serves to fill an inheritance hierarchy. Magic.

like image 182
Kerrek SB Avatar answered Sep 18 '22 21:09

Kerrek SB