tags:

views:

361

answers:

2

There are many places in boost where I see a templated class and can't help but think why the person who wrote it used templates.

For example, the mutex class(es). All the mutex concepts are implemented as templates where one could simply create a few base classes or abstract classes with an interface that matches the concept.

edit after answers: I thought about the cost of virtual functions but isn't it sometimes worth giving away very little performance penalty for better understanding? I mean sometimes (especially with boost) it's really hard to understand templated code and decrypt compiler errors as a result of misusing templates.

+18  A: 

Templates can be highly optimized at compile time, without the need for virtual functions. A lot of template tricks can be thought of as compile-time polymorphism. Since you know at compile time which behaviours you want, why should you pay for a virtual function call everytime you use the class. As a bonus, a lot of templated code can be easily inlined to eliminate even the most basic function-call overhead.

In addition, templates in C++ are extremely powerful and flexible - they have been shown to be a turing complete language in their own right. There are some things that are easy to do with templates that require much more work with runtime polymorphism.

Eclipse
+3  A: 

Templates allow you to do a generic version of an algorithm. A generic version of a container. You no longer have to worry about types and what you produce need no longer be tied to a type. Boost is a collection of libraries that tries to address the needs of a wide variety of people using C++ in their day to day lives.

dirkgently