为什么C ++ 20中引入了std :: ssize()? [英] Why is std::ssize() introduced in C++20?
问题描述
C ++ 20 介绍了 std: :ssize()
如下所示的免费功能:
C++20 introduced the std::ssize()
free function as below:
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
将cl ass C 成员函数 size()
的返回值转换为其签名的对应值。
A possible implementation seems using static_cast
, to convert the return value of the size()
member function of class C into its signed counterpart.
由于C的 size()
成员函数总是返回非负值,所以为什么有人要将它们存储在带符号的变量中?如果确实要这样做,则可以通过简单的 static_cast
来解决。
Since the size()
member function of C always returns non-negative values, why would anyone want to store them in signed variables? In case one really wants to, it is a matter of simple static_cast
.
为什么在C ++ 20中引入了 std :: ssize()
?
Why is std::ssize()
introduced in C++20?
推荐答案
本文。引号:
在C ++ 17中采用span时,它使用带符号整数作为索引和大小。部分原因是为了允许使用 -1。作为前哨值,指示在编译时大小未知的类型。但是,让STL容器的size()函数返回一个带符号的值是有问题的,因此将P1089引入到修复目录中。问题。它获得了多数支持,但没有获得共识所需的2比1保证金。
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.
本文P1227是一项建议,建议添加非成员std :: ssize和成员ssize( ) 功能。包含这些内容将使某些代码更加简单明了,并可以避免在大小计算中出现不必要的无符号性。这个想法是,如果通过std :: ssize()和作为成员函数使ssize()可用于所有容器,则对P1089的抵抗力将降低。
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 ++ 20中引入了std :: ssize()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!