Tuesday, January 6, 2009

Template MetaProgramming

While revisiting the boost library @ http://www.boost.org/ , my interest in Compile Time Template Meta Programming got rekindled. Simultaneously , i read that C++ Template mechanism is almost turing complete . ( To what extent , i do not yet know ) . That means
u can do most computations at the compile time itself , with proper tweaking and awareness of
the specific application context.

Take for example the quintessential Factorial example. I have declared
a struct which contains an enum with a Single value. There a recursive
invocation of the Factorial struct is being made.


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


Every recursive routine consists
a) a base case
b) an expression involving a recursive call

Specialize the base case and define the other things as recursive
declaration.

This is called Template specialization. This is done to terminate the recursion.


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


Here in the foo method , Factorial Template structure will
be expanded in the Compile Time !!!.... it will spit the
factorial of 4 and 0.

void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
printf("%d\t %d\n",x,y );
}

void main()
{
foo();
}


More information about Template Meta Programming can be found @ the wiki page

http://en.wikipedia.org/wiki/Template_metaprogramming

Pls. check out the Boost MPL Library and other higher order function libraries like
Lambda , Function , Functional , Binder etc...

No comments:

Post a Comment