<分区>
我偶然发现了这个关于 C++ 中整数幂的问题的答案:https://stackoverflow.com/a/1506856/5363
我很喜欢它,但我不太明白为什么作者使用一个元素枚举而不是明确地使用某种整数类型。有人可以解释一下吗?
<分区>
我偶然发现了这个关于 C++ 中整数幂的问题的答案:https://stackoverflow.com/a/1506856/5363
我很喜欢它,但我不太明白为什么作者使用一个元素枚举而不是明确地使用某种整数类型。有人可以解释一下吗?
最佳答案
据我所知,这与不允许您定义编译时常量成员数据的旧编译器有关。使用 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/