Alex Rivera | Logout

Template in C++, why have to use enum

Asked 2012-08-11T18:26:07.910
9

I have a quick question about item 48 in Scott Meyers' "Effective C++". I just don't understand the code copied from the book below,

    #include <iostream>
    using namespace std;

    template <unsigned n>
    struct Factorial
    {
       enum { value=n*Factorial<n-1>::value };
    };

    template <>
    struct Factorial<0>
    {
        enum { value=1};
    };

    int main()
    {
        cout<<Factorial<5>::value<<endl;
        cout<<Factorial<10>::value<<endl;
    }

Why do I have to use enum in template programming? Is there an alternative way to do this? Thanks for the help in advance.

Edit
Report

1 Answer

8

You could use static const int also:

template <unsigned n>
struct Factorial
{
   static const int value= n * Factorial<n-1>::value;
};

template <>
struct Factorial<0>
{
   static const int value= 1;
};

This should be fine also. The result is same in both cases.

Or you could use existing class template, such as std::integral_constant (in C++11 only) as:

template <unsigned n>
struct Factorial : std::integral_constant<int,n * Factorial<n-1>::value> {};

template <>
struct Factorial<0> : std::integral_constant<int,1> {};
answered 2012-08-11T18:28:16.870

Your Answer