Monday, May 7, 2007

Calculation using templates c++.

C++ Templates can also be used to evaluate an expression. Here i am just putting an example ( got from internet , and is working).
This template class can be used to find the factorial of a number. Actually the compiler calculates the factorial at compile time , during the template parsing.


template <int T>
class Factorial
{
public :
   // Recursive definition
   enum { GetValue = T * Factorial<T-1>::GetValue };
};


// specialization.
template <>
class Factorial<1>
{
public :
    enum { GetValue = 1 };


};

we can find the factorial using the class Factorial. For example Factorial<5>::GetValue will give the factorial of 5. Factorial of 1 is handled as a special way (Just to exit) . So the code may look like this

int fact = Factorial<5>::GetValue;

If you try to find the factorial of 0 the visual studio will crash , Not the application :), because the factorial is computed by the compiler.Because if we put zero, there is no way to exit the compilation process (check with above codes). So you may need to handle 0 as a special case. or change the specialization to Factorial<0>

Note : Use of this feature will cause to slow down the compiling process.

5 comments:

Egbert said...

Nice to meet you.I\'m from China.Can I make friends with you?

Sarath said...

The problem with Visual C++ optimizer crash can be handled by specializing the value 0 for the template class (remember the fact that 0! is 1)

msnkd said...

sarath , i have already told it :)

Sarath said...

I mean, in this above example, it is only 0 required to be specialized rather than 1.

msnkd said...

Yes thats right..