C++ Primer (5th edition) on page 240 has a note stating:
"A
constexpr
function is not required to return a constant expression".
A question has been asked about this: can constexpr function return type be a non const?. The author of that question misunderstood the note.
But what is the correct understanding of it (the answers to the cited post clarify the confusion of that post's author, but do not answer my question)?
All constexpr variables are const . A variable can be declared with constexpr , when it has a literal type and is initialized. If the initialization is performed by a constructor, the constructor must be declared as constexpr .
It means that compiler can't guarantee that your if-constexpr is always compile-time, hence the error about it. If you place all your arguments as template auto parameters of your function then it should compile well.
constexpr stands for constant expression and is used to specify that a variable or function can be used in a constant expression, an expression that can be evaluated at compile time. The key point of constexpr is that it can be executed at compile time.
In C++11, constexpr member functions are implicitly const.
A constexpr
function must return* must have a path that returns a constant expression iff all parameters are constant expressions. This actually makes sense. Example:
constexpr int square(int i){
return i*i;
}
std::array<int, square(2)> ia; //works as intended, constant expression
int i;
std::cin >> i;
int j = square(i); //works even though i is not a constant expression
std::array<int, square(i)> ia; //fails, because square does not (and cannot)
//return a constant expression
*Correction by chris.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With