How would you write a non-recursive algorithm to compute n!
?
At run time this is non-recursive. At compile time it is recursive. Run-time performance should be O(1).
//Note: many compilers have an upper limit on the number of recursive templates allowed.
template
struct Factorial
{
enum { value = N * Factorial::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}