一个成员在C++中枚举

One member enums in C++

本文关键字:C++ 枚举 成员 一个      更新时间:2023-10-16

我偶然发现了一个关于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;   
}