Question

I was trying to rewrite the Factorial implementation using constexpr function but for some reason I have no idea why I get a compile error:

recursive template instantiation exceeded maximum depth of 256

Actually I know what the error message means but what I don't is why I'm getting this error and why the code 1 using struct work but the second using function doesn't. What's the difference between them?

 // yes, I know it doesn't return the factorial value. First I want to make it compile
template <int N>
constexpr int f2()
{
    return N == 0 ? 1 : f2<N - 1>();
}

template <int N> struct Factorial
{
    enum 
    {
        value = N * Factorial<N - 1>::value
    };
};

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


int main() 
{
    x = f2<4>(); // compile error
    n = Factorial<4>::value; // works fine
}
Was it helpful?

Solution

You need a stopping state like the following:

template <>
int f2<0>()
{
   return 0;
}

since f2<N - 1>() has to be instantiated, you have your stopping state in your other case here:

template <> struct Factorial<0>

But if you are using constexpr you don't really need to use templates at all since the whole point is that it will be done at compile time, so turn it into this:

constexpr int f2(int n)
{
  return n == 0 ? 1 : (n * f2(n-1));
}

OTHER TIPS

When N == 0, the compiler still has to instantiate f2<-1> because the function call is present in the code. When f<-1> is instantiated, f<-2> is instantiated and so on. Applying this statement again and again, the compiler will keep recursing through the template until it exceeds the max depth.

You need to define a specialization of the template function to stop the recursion at the compile time rather than runtime, just as your struct version did.

template <int N>
int f2()
{
    return N * f2<N - 1>();
}

template <>
int f2<0>()
{
    return 1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top