4

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

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

4

1 回答 1

2

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;   
}
于 2013-02-19T15:45:34.947 回答