Search code examples
c++constexprstring-view

C++ using string_view in constexpr if


I want to compare string views at compile time like this:

constexpr bool isMatch(const string_view str) {
  if constexpr (str == "firstMatch"sv) {
      return true;
  } else if constexpr (str == "secondMatch"sv) {
     return true;
  }
  // ....
}

And the function is called like this:

isMatch("something"sv);

Which is obviously constant because it's right in the code.

But the compiler says that the expression inside the if constexpr 'did not evaluate to a constant'. But operator== of a string_view is constexpr. A solution would be to declare the parameter constexpr but it's not possible.

So how can I have a constexpr function that checks for these kind of matches at compile time?


Solution

  • how can I have a constexpr function that checks for these kind of matches

    Just remove the constexpr from ifs.

    constexpr bool isMatch(const string_view str) {
      if (str == "firstMatch"sv) {
          return true;
      } else if (str == "secondMatch"sv) {
         return true;
      }
      return false;
    }
    

    std::string_view::operator== is constexpr so all is fine.

    at compile time?

    Call your function in compile time context. Like:

    #include <array>
    #include <cassert>
    #include <string_view>
    using namespace std::literals;
    
    constexpr bool isMatch(const std::string_view str) {
      if (str == "firstMatch"sv) {
          return true;
      } else if (str == "secondMatch"sv) {
         return true;
      }
      return false;
    }
    
    int main() {
        std::array<int, isMatch("secondMatch"sv)> arr;
        static_assert(isMatch("firstMatch"sv));
        constexpr bool var = isMatch("No match for you!"sv);
    }
    

    In C++20 you can make sure that your function is called only at compile time with consteval.