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.