4

I stumbled upon this answer to a question about powers of integers in c++: https://stackoverflow.com/a/1506856/5363

I like it a lot, but I don't quite understand why the author uses one element enums as opposed to some integer type explicitly. Could someone explain?

Community
  • 1
  • 1
Grzenio
  • 35,875
  • 47
  • 158
  • 240

1 Answers1

2

AFAIK this has to do with older compilers not allowing you to define compile-time constant member data. With C++11 you could do

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;   
}
Michael Wild
  • 24,977
  • 3
  • 43
  • 43