Templates
Templates are notorious for the code bloating they produce. Some organisations explicitly forbid usage of templates in their internal C++ coding standards. However, templates is a very powerful tool, it is very difficult (if not impossible) to write generic source code, that can be reused in multiple independent projects/platforms without using templates, and without incurring any significant performance penalties. I think developers, who are afraid or not allowed to use templates, will have to implement the same concepts/modules over and over again with minor differences, which are project/platform specific. To properly master the templates we have to see the Assembler code duplication, that is generated by the compiler when templates are used. Let's try to compile a simple application test_cpp_templates that uses templated function with different type of input parameters:
You may notice that function func
is called with two parameters, one of type int
the other of type unsigned
. These types have both the same size and should generate more or less identical code. Let's take a look at the generated code of main
function:
Yes, indeed, there are two calls to two different functions. However, the Assembler code of these functions is almost identical. Let's also try to reuse the same function with the same types but from different source file:
The generated code is:
We see that the same functions at the same addresses are called, i. e. the linker does its job of removing duplicates of the same functions from different object files.
Let's also try to wrap the same function with a class and add one more template argument:
Please note the dummy template parameter TDummy
that is not used. Now, we add two more calls to the main
function:
Note, that the functionality of the calls is identical. The only difference is the dummy template argument. Let's take a look at the generated code:
The compiler generated calls to two different functions, binary code of which is identical.
CONCLUSION: The templates indeed require extra care and consideration. It is also important not to overthink things. The well known notion of “Do not do premature optimisations. It is much easier to make correct code faster, than fast code correct.” is also applicable to code size. Do not try to optimise your template code before the need arises. Make it work and work correctly first.
Last updated