If I write a compile-time factorial function using specialisation, the following code can suffice, and will correctly provide 120 as the result of fact1<5>()
:
template <size_t N>
constexpr size_t fact1() { return N*fact1<N-1>(); }
template <>
constexpr size_t fact1<0>() { return 1; }
However, with a single function body and the ternary operator, as in the following code, G++ 4.7 and Clang++ 3.2 both exceed their maximum template instantiation depth. It appears that 1
is never returned from fact2
. Why is it that this definition of fact2<5>()
doesn't return 120?
template <size_t N>
constexpr size_t fact2() { return N==0 ? 1 : N*fact2<N-1>(); }