Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to calculate number factorial at compile time, but without enums

Tags:

c++

templates

I want to calculate factorial at the compile-time. I found some way to solve the problem, but I want to know if there any another solution for this problem without using enum s. Here the solution using enum s.

#include <iostream>
template <int n>
struct fact
{
    enum{value = n*fact<n-1>::value};
};

template<>
struct fact<1>
{
    enum{value = 1};
};

int main()
{
    std::cout << fact<10>::value;
}

If there is no another solution, please describe why the enum s are must.

like image 386
Samvel Hovsepyan Avatar asked Jul 08 '11 07:07

Samvel Hovsepyan


2 Answers

While there are alternative notations, It's written that way because more compilers accept that enum-style notation. The language supports const integral-type class members with an inline initialization, but some compilers aren't compliant with the standard in that regard. On compilers that are compliant in this regard, the following works just fine:

#include <iostream>
template <unsigned int n>
struct fact
{   
    static const unsigned int value = n*fact<n-1>::value;
};  

template<>
struct fact<0>
{   
    static const unsigned int value = 1;
};  

int main()
{   
    std::cout << fact<10>::value << "\n";
}   
like image 130
David Hammen Avatar answered Sep 19 '22 07:09

David Hammen


Replace,

enum{value};

with,

static int const value; // or unsigned int

enums are must because they suppose to be resolved at compile time. Which assures that whatever result you calculated must have been done at compile time. Other such type is static int const (means any integral type).

To illustrate:

enum E {
 X = strlen(s); // is an error, because X is a compile time constant
};
like image 34
iammilind Avatar answered Sep 22 '22 07:09

iammilind