-1

How to calculate some mathematical expression i.e. finding factorial of n; during compiletime in c++ ?

Jekin
  • 79
  • 1
  • 8
  • http://en.wikipedia.org/wiki/Template_metaprogramming – Henrik Oct 19 '12 at 07:29
  • http://stackoverflow.com/questions/3082113/calculating-factorial-using-template-meta-programming – Alexander Tobias Bockstaller Oct 19 '12 at 07:30
  • Besides template metaprogramming, you could probably use c++11 [`constexpr`](http://en.wikipedia.org/wiki/C%2B%2B11#constexpr_-_Generalized_constant_expressions) and recursion. Unfortunately I cannot check this right now. – juanchopanza Oct 19 '12 at 07:33
  • This is too much of a homework-style question, plus the reader was rude enough to downvote those who gave links as answers, he doesn't want do any research, he wanted it down for him.. – CashCow Oct 19 '12 at 07:40

2 Answers2

2

Here is a wiki article about template meta-programing in C++.

Here is another wiki article about compile-time function execution.

Here is a SO question regarding the factorial.

Let's take the wiki xample of computing factorial in compile-time.

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

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

// Factorial<4>::value == 24
// Factorial<0>::value == 1
const int x = Factorial<4>::value; // == 24
const int y = Factorial<0>::value; // == 1

Since all of the arguments needed are known in the compile time (they are explicitly mentioned in Factorial<4>, for example), the compiler is able to generate all the needed code. After that, the value of the Factorial<4> struct will be 24 which can be later used as if you've hardcoded it yourself.

Community
  • 1
  • 1
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
-1

Welcome to the so-called template meta-programming.

This page describes what it is. It has a specific example to calculate the factorial of an integer in compile-time.

valdo
  • 12,632
  • 2
  • 37
  • 67