The Secret Life of C++: Templates

Template code basically just tells the compiler to generate multiple copies of the code, one for each set of arguments.

Simple template

Here is a simple template for the max function, and an instantiation of it:

        

        

        

        

        
Symbol list:
_Z3maxIiET_S0_S0_
max<int> instantiation.
_Z3maxIdET_S0_S0_
max<double> instantiation.
_Z3maxI9my_structET_S1_S1_
max<my_struct> instantiation.
_Z3maxIbET_S0_S0_
max over bool.

Specialization

Template specialization is just a clarification to the compiler. Of course, if you instantiate a specialization of a template, you get the specialized code.

Templated Class Methods

Lets look at how templated class methods work:

        

        

        

        

        

Pretty straight forward. You end up with a mangled symbol that includes both types, something like:

_ZN9my_structIdE14set_field_fromIiEEvT_
my_struct<double>::set_field_from<int>(void)
And of course there is no way to have a templated virtual method, which is mildly annoying but somewhat understandable.

Recursive Templating

So templating is just pattern matching. We can use this to do strange tricks. The standard trick is computing Fibonacci numbers at compile time:

        

        

        

        

        

As we can see from this example, the computation is done at compile time, and the result (2584) is placed in the binary directly.

TODO: Exceeding the template depth.

TODO: Pointer to modern template metaprogramming link.

Fork me on GitHub