When is std::string_view::operator== really constexpr?
When is std::string_view::operator== really constexpr?
根据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.
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 多成员Constexpr结构初始化
- 条件constexpr函数
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- Visual C++ constexpr Hints
- 如何确认我的constexpr表达式实际上已经在编译时执行
- 为什么constexpr的性能比正常表达式差
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 为什么std::isnan 不是 constexpr?
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 更多constexpr容器是否需要mark_immutable_if_consexpr
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- constexpr上下文中std::initializer_list的验证
- constexpr构造函数需要常量成员函数时出现问题
- vs 2015 constexpr变量不恒定,但与2019相比还好吗
- C++constexpr实现差异
- 添加静态constexpr成员是否会更改结构/类的内存映射
- When is std::string_view::operator== really constexpr?