Saturday, 28 March 2009

A Poem on Metaprograms

Compiler, Compiler, Burning Bright,
In the template struct of night.
What immortal metaprogram,
Can frame thy fearful factorial.
In what template struct enum,
Inductive definition looms.
From the general to the specific,
The blessed base case blooms.

Example

The classic example of TML is the factorial function, i.e. fact(n)= if n is zero ret 1 else return n* factorial(n-1).

template <int N>
struct Factorial { enum { value = N * Factorial<N - 1>::value }; };

template <>
struct Factorial<0> { enum { value = 1 }; };

To print factorial values, do something like the following: int x = Factorial<4>::value; // == 24.

There are TWO parts to Template Metaprogramming, template definition and template instantiation.

Analysis

Compile-time versus execution-time tradeoff: longer to compiler, faster to execute!

Libraries

Boost MPL can be used in MSVC. Here's a tutorial.

TML is generally Turing-complete, any computation expressible by a computer program can be expressed by a template metaprogram.

No comments: