开发者

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

开发者 https://www.devze.com 2023-03-18 00:22 出处:网络
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

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.


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";
}   


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
};


Alternatively, you can use static const members:

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

精彩评论

暂无评论...
验证码 换一张
取 消