Is it possible to compare std::string_view using "if constexpr" in a constexpr context? And why is_hello_2 and is_hello_4 fail to compile showing error: "‘s’ is not a constant expression"
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;
};
Considering the main function (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;
}
Is there a way to fix "is_hello_2" and "is_hello_4"?
Is there a way to fix "is_hello_2" and "is_hello_4"?
Remove the constexpr
from if
s in is_hello_2
or is_hello_4
.
How to compare string_view using if-constexpt in a constexpr context
Normally, like anywhere else.
static constexpr bool is_hello_5() {
constexpr const std::string_view s1 ("hello");
if constexpr (s1 == "hello") {
return true;
}
return false;
}
Function arguments values are not constant expressions and you can't use them in a if constexpr
.
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