【发布时间】:2020-10-21 08:35:39
【问题描述】:
使用以下两个函数,它们往往会在编译时获取字符串文字的长度。第一个不会编译,虽然例子没有意义,但是我实际上需要使用getlen内的字符串长度作为编译时常量,我该怎么做? p>
// 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;
}
第二个函数显示getlen2的返回确实是一个constexpr,所以一定是s。这怎么解释?
【问题讨论】: