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:
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 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));
}
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;
}