The Secret Life of C++: Day 3: Basic 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: template-max.cc, template-max.s, template-max.listing. 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: templated-method.cc, templated-method.s, templated-method.listing.

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: fibonacci.cc, fibonacci.s, fibonacci.listing.

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

More information about cute template tricks is available at boost.org. I highly recommend reading through their stuff. Some of it is over the top (eg, Lambda), but much of it is useful and educational.


Richard Tibbetts
Last modified: Wed Jan 21 17:36:31 EST 2004