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...

Wednesday, December 31, 2008

Why this Blog ?

The C++ Programming Language was the foremost multi-paradigm programming language of the 1990s and there has been a steady decline of it's share in the programming language space. Virtual Machine programming languages with automatic memory management is the trend of the first decade of the twenty first century. Having
spent a deal of time mastering the language and working with it for a period of 10 years, i threw in the towel and moved to Java and C#.

I suspect C++ is still the best vendor neutral , cross platform language avaiable in the world. With the addition of TR1 and upcoming C++ 0x , C++ programming will be making a come back to it's prominence in the multi core /multi processor world.

Now , i am (re)-learning C++