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>(); }
The problem here is that no matter what,
fact2<N-1>will always be instantiated (even non-executed paths need to be compiled, see Effective C++, I think Item 47 or 48). You need to, somehow, make it only instantiate the next function if you’re not at the end. One way would be to just say “screw templates” and go the usualconstexprway as @NicolBolas says in his comment.Another would be using one of the techniques used in this similar question.