How to calculate some mathematical expression i.e. finding factorial of n; during compiletime in c++ ?
Asked
Active
Viewed 181 times
-1
-
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 Answers
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
-
-
@mugen well the answer isn't really detailed too, and the OP doesn't show any research attempt. Not to mention this is partially a duplicate. – SingerOfTheFall Oct 19 '12 at 07:34
-
2[See here](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers) (I didn't downvote though). – Jesse Good Oct 19 '12 at 07:35
-
I think it is better to flag questions accordingly than to answer with half a sentence. But that is just my opinion. – matthias krull Oct 19 '12 at 07:38