Alex Rivera | Logout

Template or abstract base class?

Asked 2009-03-02T14:49:41.240
40

If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

  • Use an abstract base class and pass concrete object in
  • Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

class Brake {
public: virtual void stopCar() = 0;  
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};

Version 2a: Template

template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};

Version 2b: Template and private inheritance

template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

Edit
Report

1 Answer

0

Personally I would allways prefer to use Interfaces over templates because of several reasons:

  1. Templates Compiling&linking errors are sometimes cryptic
  2. It is hard to debug a code that based on templates (at least in visual studio IDE)
  3. Templates can make your binaries bigger.
  4. Templates require you to put all its code in the header file , that makes the template class a bit harder to understand.
  5. Templates are hard to maintained by novice programmers.

I Only use templates when the virtual tables create some kind of overhead.

Ofcourse , this is only my self opinion.

answered 2009-04-10T10:42:38.573

Your Answer