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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With