根據cppreference,std::string_view::operator==
是constexpr。在當前的庫實現中,我無法找到這種情況。什麼時候是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-幹線,這並不因爲++的libstdc操作編譯==完全不constexpr。
使用clang-trunk時,這也失敗了,因爲operator ==()被聲明爲constexpr,但使用char_traits :: compare()而不是constexpr。
標準庫中存在這些錯誤嗎?或者我的期望錯了?
如果我的期望錯了,那我該如何構造一個可以進行constexpr比較的string_view?
猜測沒有編譯器完全符合C++ 17。部分原因是目標仍在移動,委員會下週舉行了一次會議(https://isocpp.org/blog/2016/07/n4608)來解決問題。 –
當前的實現可能使用'char_traits :: compare'來進行比較。它的運行速度比運行時的手動循環快。它可能可以用一些內在的東西來完成。 –
DeiDei
根據[N3762](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3762.html),'operator =='被聲明爲沒有'constexpr'。 – kakkoko