With the following two functions which is tend to get the length of a string literal at compile time. The first one won't compile, though the example is meaningless, but I actually need to use the string length inside the getlen as a compile-time constant, how can I do that?
// compile failed with "expression did not evaluate to a constant" in vs2019 std=latest
// failure was caused by a read of a variable outside its lifetime
// see usage of 's'
constexpr auto getlen(const char* s) {
constexpr auto size = std::char_traits<char>::length(s);
return size;
}
constexpr auto getlen2(const char* s){
return std::char_traits<char>::length(s);
}
int main() {
constexpr size = getlen2("suprise!") // size is 8
return 0;
}
The second function shows that the returns of getlen2 is indeed a constexpr, so must be the s. How to explain this?