什么时候是std :: string_view :: operator ==真的是constexpr?

Rum*_*rak 13 c++ gcc libc++ c++17

根据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);
}
Run Code Online (Sandbox Code Playgroud)

使用gcc-trunk,这不会编译,因为在libstdc ++中,operator ==根本不是constexpr.

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

这些错误是否在标准库中?或者我的期望是错的?

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

Mar*_*low 11

string_view::operator==char_traits<CharT>::compare做比较. std::char_traits<char>::compare不是constexpr,所以operator ==不是constexpr.

如果你使用一个实现char_traitsconstexpr的实现compare,那么比较将是constexpr.

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

  • 保持我的手指交叉那张纸!你知道`char_traits`的可用实现已经实现了contexpr`compare`吗? (4认同)