我一直在 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 == extent
是true
,并且remove_pointer_t<decltype(data(arr))>(*)[]
可转换为ElementType(*)[]
。
因此,我们已经有了正确的约束。只是在这些情况下,data(arr)
实际上并不依赖于这些情况,因此约束很容易得到满足。我们只需要制作这些模板。