|
为什么在C++20中引入std::ssize()
std::ssize():
template <class C>
constexpr auto ssize(const C& c)
-> std::common_type_t<std::ptrdiff_t,
std::make_signed_t<decltype(c.size())>>;
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 &#34;-1&#34; 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 &#34;fix&#34; the problem. It received majority support, but not the 2-to-1 margin needed for consensus.
当span被C++17采用时,它使用一个有符号整数作为索引和大小。 部分原因是允许使用“-1”作为标记值,以指示在编译时大小未知的类型。 但是,如果STL容器的size()函数返回一个有符号的值,则会出现问题,因此引入P1089来“修复”这个问题。 它得到了多数支持,但没有达到达成共识所需的2比1的比例。
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.
本文P1227建议添加非成员std::ssize和成员ssize()函数。 包含这些元素将使某些代码更加直接,并允许避免在大小计算中出现不需要的无符号。 其想法是,如果ssize()可用于所有容器,无论是通过std::ssize()还是作为成员函数,那么对P1089的阻力都会降低。
可以这么写:
for(int i = 0; i < container.ssize() - 1; ++i) |
|