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

时间:2016-11-04 10:00:21

标签: c++ gcc c++17 libc++

根据cppreferencestd::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 ++中,operator ==根本不是constexpr。

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

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

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

1 个答案:

答案 0 :(得分:11)

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

如果您使用实现constexpr char_traits的{​​{1}}实现,那么比较将是constexpr。

请注意,标准委员会面前有一篇论文建议compare(和该类别的其他方法)constexpr。

相关问题