gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:58:36 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com