How to decide when to implement a C++ template?
I'm coming from C, and getting deeper and deeper into C++. Using the container classes of the standard library, as-well as the smart pointer classes from the boost library, I've had my first introduction to class templates. I use them a lot now.
Recently I made my first approach of writing my own class templates. But 99% of what I can think of, where a class template might be useful, the class template already exists in the standard library or one of the boost libraries.
When do you decide to implement something as a class template? What is your criteria? Do you have an example?
C++ proposes several programming paradigms, as you have discovered, and they are not exclusive.
What you write with templates could generally be written with Object-Oriented codes, so it's usually a matter of trade-off.
The C++ templates follow the Generic Programming paradigm, the idea is that your class / method will be able to work with any type, as long as the instances of this type follow a Concept.
The first striking difference, with regard to Object-Oriented code, is that there is no need for a common base class. In fact, combining templates and free-functions, you can effectively work with an heterogeneous set of objects.
That is therefore when they shine:
- If you have an heterogeneous set of objects with which you want to work
- If refactoring them is not possible (for various reasons)
then using a template seems a very good idea.
Generally speaking, I've mainly created them either for small utilities or for frameworks. In "business" code I use them, but I rarely define new ones. For example:
- box::Enum<typename EnumType> which wraps an enum an proposes seamless conversion to/from string (useful for pretty printing in the logs), serialization and the like
- box::Identifier<typename T> which wraps an integer (essentially) and allow me to create a hierarchy of identifiers types similar to the hierarchy of types, so that a DummyObjectId can be passed when one would expect an ObjectId, but not the other way around
In general, there are therefore two situations in which I used templates:
- preventing copy/pasting
- increasing type safety
If you find yourself in one of those, perhaps could you think about it.