gpt4 book ai didi

c++ - std::大小为零的数组

转载 作者:可可西里 更新时间:2023-11-01 18:20:00 25 4
gpt4 key购买 nike

std::array<int,0> 是什么意思? ,大小为零的数组?

在发布之前,我已经在 SO 中解决了类似的问题,所有这些问题是关于简单数组类型和 C 语言的,他们中的大多数人说这是非法的。但在 C++ 中 array<int,0>是允许的。

根据 cppreference.com

There is a special case for a zero-length array (N == 0). In that case, array.begin() == array.end(), which is some unique value. The effect of calling front() or back() on a zero-sized array is undefined.

为什么不定义为非法?

最佳答案

What does it mean to have std::array,array of size zero?

与空的 std::vector 或空的 std::set 相同。

Why isn't it defined as illegal?

让它合法化是可取的,因为这意味着泛型编程不必处理 std::array 时的特殊情况的大小是编译时计算的结果。

由于模板专门化,可能将其定义为合法。例如,Visual C++ 附带的实现以类似于以下的方式专门化了 std::array:

template<class T>
class array<T, 0> // specialisation
{
// ...

size_type size() const
{
return 0;
}

T elements[1]; // the raw array cannot have a size of 0
};

我想每个编译器都像那样实现 std::array

关于c++ - std::大小为零的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28929165/

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