When should I use templates instead of inheritance, and vice versa?

Viewed 6988

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?

4 Answers
Related