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"?
Remove the
constexpr
fromif
s inis_hello_2
oris_hello_4
.Normally, like anywhere else.
Function arguments values are not constant expressions and you can't use them in a
if constexpr
.