In many situations, the question doesn't even ask itself, since sometimes inheritance provides necessary features which templates can't provide. For example, when I need to address different types via one base-type (polymorphism), I need to use inheritance.
However, there are some instances where the problem can be solved both with inheritance, as well as templates.
Take for example strategy pattern-like parametrization of certain parts of the code:
One solution of a file-parser could look like this:
class FileParser
{
//...
public:
void Parse(ParsingAlgorithm* p);
//...
}
void FileParser::Parse(ParsingAlgorithm* p)
{
m_whatevertypeofvaluesineed = p->Parse(whateverparametersyouneed);
}
where ParsingAlgorithm is an abstract base class, which provides some basic methods and needs to be inherited by whoever likes to implement a specific parser for the FileParser class.
However, the same can easily be achieved using templates:
template <class Parser>
class FileParser
{
//...
public:
void Parse()
{
m_whatevertypeofvaluesineed = m_parser.Parse(whateverparametersyouneed);
}
private:
Parser m_parser;
//...
}
Are there some general rules that I can use to decide whether to use templates or inheritance? Or should I simply use templates wherever possible, in order to avoid run-time overhead of things like virtual functions?
Templates can be used in conjunction with abstract datatypes in order to allow them to handle any type of data. For example, you could make a templated stack class that can handle a stack of any datatype, rather than having to create a stack class for every different datatype for which you want the stack to function.
Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. To simply put, you can create a single function or single class to work with different data types using templates. C++ template is also known as generic functions or classes which is a very powerful feature in C++.
If you know during compile-time what objects you're going to manipulate, then static polymorphism with templates is often the fastest way to go, and it produces code that's a little bit more concise (no need for explicit inheritance). It can also be more generic as you're not restricted to a strong class hierarchy.
If you want run-time polymorphism, then you have no choice but to use pointers, inheritance and the slight overhead of virtual functions.
My own opinion:
Templates provide compile-time polymorphism as opposed to run-time polymorphism provided by inheritance. I prefer using templates when I can.
This article on Templates and Inheritance explains it in detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With