In the following if I use constexpr the compiler apparently the compiler says "expression must have a constant value", this happens on MSVC and GCC:
int main() {
constexpr auto nnn = {
"this", "sentence", "is", "not", "a", "sentence",
"this", "sentence", "is", "a", "hoax"
};
}
Without the constexpr the compiler can deduce that nnn variable is an std::initializer_list<const char*>. And the std::initialiser_list class has a constexpr constructor, why can't this be constexpr?
Type deduction is not failing. The compiler is deducing auto to std::initializer_list<const char*>. You get the same result if you wrote std::initializer_list<const char*> instead of auto.
The initialization fails to be a constant expression (something that can only be checked after all types have been deduced).
It fails to be a constant expression, because std::initializer_list works as if an array with the same storage duration was defined in the same scope to hold the elements and as if the std::initializer_list object held pointers to the beginning and end of that array.
Because that array would have automatic storage duration in your example, the initialization of the std::initializer_list object can't be a constant expression, because the result of a constant expression can only contain pointers to objects with static storage duration. (The value of pointers to an object with automatic storage duration would change each time the initialization is performed, so can't be constant expression results.)
You can force the unnamed array to have static storage duration (as well as the std::initializer_list) by using static:
int main() {
constexpr static auto nnn = {
"this", "sentence", "is", "not", "a", "sentence",
"this", "sentence", "is", "a", "hoax"
};
}
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