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 C 的 size()
成员函数的返回值转换为其有符号的对应的。
既然 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/