Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare string_view using if-constexpt in a constexpr context

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"?

like image 527
Equod Avatar asked Dec 13 '22 07:12

Equod


1 Answers

Is there a way to fix "is_hello_2" and "is_hello_4"?

Remove the constexpr from ifs 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.

like image 137
KamilCuk Avatar answered Apr 20 '23 01:04

KamilCuk