Simple C ++ 11 constexpr factorial with triple exceeds maximum template depth

If I write a compilation time factorial function using specialization, the following code may be sufficient and will correctly provide 120 as a 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 one function body and ternary operator, as in the following code, g ++ 4.7 and Clang ++ 3.2 both exceed the maximum depth of the template increment. It seems like 1 never returns from fact2 . Why does this definition of fact2<5>() not return 120?

 template <size_t N> constexpr size_t fact2() { return N==0 ? 1 : N*fact2<N-1>(); } 
+4
source share
1 answer

The problem is that no matter what, fact2<N-1> will always be created (even non-executable paths must be compiled, see Effective C ++, I think paragraph 47 or 48). You need to somehow do this only to create the next function, if you're not at the end. One way is to simply say β€œscrew patterns” and go in the usual way constexpr , as @NicolBolas says in his comment.

Another will use one of the methods used in this similar question .

+7
source

Source: https://habr.com/ru/post/1432156/


All Articles