Typedef or template ?

Every once in a while I see c++ templates being used in code that has only one single type to pass into the template. This type might change in future application versions, but it is forseeable that it will always be one and the same for the whole application. In this case I always ask myself why the developer hadn’t chosen a typedef instead.

Example: If a class processes the float data type and for future versions shall also be prepared to process double types – but a mix of float and double is no use case. In this case using a typedef offers the same degree of versatility – without the drawbacks of template programming. As drawbacks I see a higher code-complexity and a tendency to write code in .h files that belongs to .cpp files (although it is possible to split up .h and .cpp files also for templates – if one chooses a fixed set of types to be compiled in – but that’s a topic for another blog …).

Don’t get me wrong, there are many situations where templates are justified: If several types have to be processed by the same class and in the same application. Or if an independent binary library isn’t supposed to be recompiled for an application-specific set of types. But, again, a template should not be used if it will be compiled for only one type in an application (and if it is forseable that it will always be only one). If the type might change, but the amount of supported types will remain 1: Use typedef as long as you can.