This question already has answers here:
static const Member Value vs. Member enum : Which Method is Better & Why?

(7 个回答)


8年前关闭。




我偶然发现了一个关于 c++ 中整数幂的问题的答案:https://stackoverflow.com/a/1506856/5363

我很喜欢它,但我不太明白为什么作者使用一个元素枚举而不是明确的某些整数类型。有人能解释一下吗?

最佳答案

AFAIK 这与不允许您定义编译时常量成员数据的旧编译器有关。使用 C++11 你可以做到

template<int X, int P>
struct Pow
{
    static constexpr int result = X*Pow<X,P-1>::result;
};
template<int X>
struct Pow<X,0>
{
    static constexpr int result = 1;
};
template<int X>
struct Pow<X,1>
{
    static constexpr int result = X;
};

int main()
{
    std::cout << "pow(3,7) is " << Pow<3,7>::result << std::endl;
    return 0;
}

关于c++ - C++ 中的一个成员枚举,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14961368/

10-11 22:10
查看更多