Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is std::string_view::operator== really constexpr?

According to cppreference, std::string_view::operator== is constexpr. I have trouble finding a situation for this to be true with current library implementations.

Here's what I tried:

#include <string_view>

constexpr char x0[] = "alpha";
constexpr char y0[] = "alpha";
constexpr auto x = std::string_view(x0, 5);
constexpr auto y = std::string_view(y0, 5);

constexpr auto a = std::string_view("alpha", 5);
constexpr auto b = std::string_view("alpha", 5);

int main()
{
  // a, b, x, y are all constexpr, operator== is constexpr
  // therefore I expected this to compile:
  static_assert(x == y);
  static_assert(a == b);
}

With gcc-trunk, this does not compile because in libstdc++ the operator== is not constexpr at all.

With clang-trunk this also fails because operator==() is declared constexpr, but uses char_traits::compare() which is not constexpr.

Are these bugs in the standard libraries? Or are my expectations wrong?

If my expectations are wrong, then how can I construct a string_view that can be constexpr-compared?

like image 422
Rumburak Avatar asked Nov 04 '16 10:11

Rumburak


1 Answers

string_view::operator== uses char_traits<CharT>::compare to do the comparison. std::char_traits<char>::compare is not constexpr, so the operator == is not constexpr.

If you use an implementation of char_traits that implements a constexpr compare, then the comparison will be constexpr.

Note that there is a paper in front of the standards committee which proposes to make std::char_traits<>::compare (and other methods of that class) constexpr.

like image 115
Marshall Clow Avatar answered Oct 21 '22 17:10

Marshall Clow