Equ*_*uod 4 c++ string-view c++20 if-constexpr
是否可以在 constexpr 上下文中使用“if constexpr”来比较 std::string_view ?以及为什么 is_hello_2 和 is_hello_4 无法编译显示错误:“'s' 不是常量表达式”
static constexpr bool is_hello_1(auto s) {
return s == "hello";
}
static constexpr bool is_hello_2(auto s) {
if constexpr (s == "hello") {
return true;
}
return false;
}
static constexpr auto is_hello_3 = [](auto s) {
return s == "hello";
};
static constexpr auto is_hello_4 = [](auto s) {
if constexpr (s == "hello") {
return true;
}
return false;
};
Run Code Online (Sandbox Code Playgroud)
考虑到主要功能(https://godbolt.org/z/zEcnb8):
int main(int argc, char **argv) {
static constexpr const std::string_view s1 ("hello");
if constexpr (s1 == "hello"){}
if constexpr (is_hello_1(s1)){}
// if constexpr (is_hello_2(s1)){} // <- doesn't compile
if constexpr (is_hello_3(s1)){}
// if constexpr (is_hello_4(s1)){} // <- doesn't compile
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法修复“is_hello_2”和“is_hello_4”?
有没有办法修复“is_hello_2”和“is_hello_4”?
删除constexprfrom ifs inis_hello_2或is_hello_4。
如何在 constexpr 上下文中使用 if-constexpt 比较 string_view
通常,就像其他任何地方一样。
static constexpr bool is_hello_5() {
constexpr const std::string_view s1 ("hello");
if constexpr (s1 == "hello") {
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
函数参数值不是常量表达式,您不能在if constexpr.
| 归档时间: |
|
| 查看次数: |
453 次 |
| 最近记录: |