Fun with C++ template metaprogramming
24 Jan 2014Template metaprogramming in C++ is neat!
It lets you write programs that you can get the compiler to execute at compile time. Here’s a basic example showing how to get the compiler to calculate the greatest common divisor of two numbers:
At first glance, this isn’t anything too interesting, until you realise the the value GCD<25, 60>
is replaced with the calculated result and ends up as a static const int
with a value of 25.
Moving on, this is a basic fibonacci generator that runs at compile time.
If you squint, it looks like templates can be used as functions, types as function arguments and fields (or typedefs) in the templated structure as your result.
With this in mind, think of how similar the previous code example looks when compared with the following Haskell code snippet:
Neat! They seem to line up fairly closely when looking at it this way.
The key to writing recursive templates like this is to use template specialisation as your base case to terminate the recursion. It’s like pattern matching in Haskell to determine which function definition to use.
Normally, you’d write the templates in a separate C++ header and then include them into the main program, so I’ll do that in the following examples.
Here’s a definition for an IF function in C++ templates:
Here, we’ve built a template with two specialisations, one for the IF clause and one for the ELSE clause. We’ve used typedefs to pick out the supplied clauses from the template arguments to determine the result.
In the next post in this series, I’ll extend these ideas into building lists with templates, and then doing interesting operations (map, reduce and sort) on them, all at compile time.
Full code for the above is available on GitHub