为什么span的数组和std::array构造函数与其容器构造函数不同

Why are span's array and std::array constructors different from its container constructors

本文关键字:构造函数 array span 数组 std 为什么      更新时间:2023-10-16

我一直在 Godbolt 上使用 clang trunk 和 libc++ 进行最新的std::span规范,发现一些构造函数令人困惑。

特别是,我发现来自普通旧数组和std::array的构造函数与其他容器不同。

例如,以下代码似乎要编译:

std::vector<int*> v = {nullptr, nullptr};
std::span<const int* const> s{v};

但是,这不会:

std::array<int*, 2> a = {nullptr, nullptr}; 
std::span<const int* const> s{a};

这似乎与 cppreference.com 上描述构造函数的方式一致,我只是在努力理解为什么会这样。有人能说出什么光吗?

这似乎是一个疏忽。数组构造函数当前指定为:

template<size_t N> constexpr span(array<value_type, N>& arr) noexcept;
template<size_t N> constexpr span(const array<value_type, N>& arr) noexcept;

但可能应该指定为:

template<class T, size_t N>
requires std::convertible_to<T(*)[], ElementType(*)[]>
constexpr span(array<T, N>& arr) noexcept;
template<class T, size_t N>
requires std::convertible_to<const T(*)[], ElementType(*)[]>
constexpr span(const array<T, N>& arr) noexcept;

这将使您的示例编译,因为它是安全的。我提交了LWG问题。现在是 LWG 3255。


措辞已经在[span.cons]/11 中指定了此约束:

template<size_t N> constexpr span(element_type (&arr)[N]) noexcept;
template<size_t N> constexpr span(array<value_type, N>& arr) noexcept;
template<size_t N> constexpr span(const array<value_type, N>& arr) noexcept;

约束条件

  • extent == dynamic_­extent || N == extenttrue,并且
  • remove_­pointer_­t<decltype(data(arr))>(*)[]可转换为ElementType(*)[]

因此,我们已经有了正确的约束。只是在这些情况下,data(arr)实际上并不依赖于这些情况,因此约束很容易得到满足。我们只需要制作这些模板。