Sometimes, when multiple types are sent as template parameters, some information about the types needs to be interrogated to be able to configure another property of the template. The STL’s type traits header does a good job of supplying many of the more useful ones, but there is room for extension. Say, for instance, the template implements a type of variant container; a type of smart union. The container may store one of several types declared in the template parameter list. We need to allocate storage for this, but how determine the size?
We can use template meta programming to help us here.
Here I will show you two variations; one for pre C++11 compilers that don’t support variadic templates and one for those that do.
Let’s say that we want to be able to handle up to four types. The ‘= void’ allows one, two, three or four types to be specified.
First, let’s create a helper template to determine the largest of two types.
These templates will define their ‘type’ to either that of TrueType or FalseType dependent on the condition supplied.
Next we create a recursive typedef that chooses the largest type between the first template parameter type and all of the rest. We typedef ‘all of the rest’ for clarity.
Now the recursive bit.
The compiler will recursively parse the template until there is one type to test. Here we need something to stop the compiler attempting to parse any further.
What we do is to add a specialisation for the final single type.
Putting this all together we get…
How It’s Used
The number of types that can be handled is easily increased.
This is the technique used in the Embedded Template Library to implement largest/smallest traits.
In the next post I’ll show you how to achieve the same with variadic templates.