3

As we know, when constexpr function's return value cannot be known at compile-time, it will be delayed to be computed at run-time(IOW, decay to non-constexpr function). This allows us to adhere constexpr to a function freely and need not worry about any overhead.

I think it can also apply to if statement. Since c++17, we have if constexpr, so we can use compile-time if statement easily(without true_type/false_type. Unlike constexpr function, however, it will fail if its condition cannot be known at compile-time:

constexpr int factorial(int n)
{
    if constexpr(n == 0) return 1;
    else return n * factorial(n-1);
}

So, the codes above cannot pass compilation because n is not a constant expression. But certainly, the function can be calculated at compile-time when input is known at compile-time.

Chen Li
  • 4,824
  • 3
  • 28
  • 55
  • 2
    I think your example might be made more compelling by using a `constexpr int factorial` function with a `constexpr if (v==0)`. – MSalters Jun 19 '18 at 11:21
  • @MSalters Thanks! Edited that in. – Chen Li Jun 19 '18 at 11:55
  • @陳力 Like your example code you don't need `if constexpr`. A regular `if` is all that is needed. The main use of `if constexpr` is when the branch that would not be executed would not compile. – NathanOliver Jun 19 '18 at 12:42
  • [quora](https://www.quora.com/From-a-language-design-level-why-doesnt-if-constexpr-decay-to-trival-if-when-the-condition-cannot-be-deduced-at-compile-time/answer/Joe-Zbiciak?__filter__=&__nsrc__=2&__snid3__=2745481457) has an excellent answer. – Chen Li Jun 21 '18 at 10:07

1 Answers1

1

For the same reason that swallowing errors/exceptions and just plowing through is bad. It can potentially put your program in some sort of unspecified state. Making it almost impossible to reason about.

If a constraint in a program isn't met, the person who wrote it and relied on it needs to be notified promptly. Making such a thing a hard error for a language construct makes sense. Especially if the language construct drive the actual generation of code.

In this case the constraint is b being a valid constant expression.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458