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

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

本文关键字:really constexpr operator is std string When view      更新时间:2023-10-16

根据cppreference, std::string_view::operator==为constexpr。我很难在当前的库实现中找到这种情况。

这是我尝试的:

#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);
}

对于gcc-trunk,这不会编译,因为在libstdc++中,操作符==根本不是constexpr。

对于clang-trunk,这也会失败,因为operator==()被声明为constexpr,但使用的是char_traits::compare(),而不是constexpr。

这些bug在标准库中吗?还是我的期望错了?

如果我的期望是错误的,那么我如何构造一个可以进行constexr比较的string_view ?

string_view::operator==使用char_traits<CharT>::compare进行比较。std::char_traits<char>::compare不是constexpr,所以operator ==不是constexpr。

如果您使用char_traits的实现实现了constexpr compare,那么比较将是constexpr。

请注意,在标准委员会面前有一篇论文建议使std::char_traits<>::compare(以及该类的其他方法)constexpr.