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.