c++ - 为什么在 C++20 中引入了 std::ssize()?

标签 c++ stl unsigned signed c++20

C++20引入std::ssize() free 函数如下:

template <class C>
    constexpr auto ssize(const C& c)
        -> std::common_type_t<std::ptrdiff_t,
                              std::make_signed_t<decltype(c.size())>>;

一个可能的实现似乎是使用 static_cast,将 class Csize() 成员函数的返回值转换为其有符号的对应的。

既然 C 的 size() 成员函数总是返回非负值,为什么有人想将它们存储在有符号变量中?万一真的想要,这只是一个简单的static_cast

为什么在C++20中引入std::ssize()

最佳答案

基本原理在 this paper 中描述。 .引用:

When span was adopted into C++17, it used a signed integer both as an index and a size. Partly this was to allow for the use of "-1" as a sentinel value to indicate a type whose size was not known at compile time. But having an STL container whose size() function returned a signed value was problematic, so P1089 was introduced to "fix" the problem. It received majority support, but not the 2-to-1 margin needed for consensus.

This paper, P1227, was a proposal to add non-member std::ssize and member ssize() functions. The inclusion of these would make certain code much more straightforward and allow for the avoidance of unwanted unsigned-ness in size computations. The idea was that the resistance to P1089 would decrease if ssize() were made available for all containers, both through std::ssize() and as member functions.

关于c++ - 为什么在 C++20 中引入了 std::ssize()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56217283/

相关文章:

c++ - 如何获取列表中的倒数第二个元素?

c++ - 指向常量数组的指针的正确定义是什么?

c++ - 查找 UP 和 DOWN 机器的 C 程序。

c++ - make_heap() 函数参数——如果我不想包含某些元素怎么办?

c++ - 带有 std::priority_queue 的最小堆是我的瓶颈

c++ - unsigned int有效位数

c++ - 这个长长的 "if argA == argB do ..."列表还有其他选择吗?

c++ - 使用标准库用 strtok 替换循环

java - 在 Java 中使用 char 作为无符号的 16 位值?

c - uint32_t 到 int32_t 的快速不安全转换