无法从临时 std::array 构造 std::span<int><int>

问题描述 投票:0回答:1

我有以下代码,我希望它能工作,但它没有:

#include <array>
#include <span>

auto f = std::span<int>(std::array<int, 3>{});

clang 无法编译此:

error: no matching conversion for functional-style cast from 'std::array<int, 3>' to 'std::span<int>'
auto f = std::span<int>(std::array<int, 3>{});
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

note: candidate template ignored: constraints not satisfied [with _Tp = int, _ArrayExtent = 3]
        span(const array<_Tp, _ArrayExtent>& __arr) noexcept
        ^

我希望这会调用构造函数:

template< class U, std::size_t N >
constexpr span( const std::array<U, N>& arr ) noexcept; // (6)

4-6) 构造一个跨度,它是数组 arr 的视图;生成的跨度有

size() == N
data() == std::data(arr)

仅当

extent == std::dynamic_extent || N == extent
true
且从
std::remove_pointer_t<decltype(data(arr))>
element_type
的转换至多是限定转换时,这些重载才参与重载决策。

请参阅 cppreference 上的

std::span::span

为什么这个构造函数的约束不满足?

  • extent == std::dynamic_extent
    对于
    std::span<int>
    ,所以显然满足第一个要求
  • std::remove_pointer_t<decltype(data(arr))>
    就是
    int
    ,等于
    std::span<int>::element_type = int
    ,所以也满足了第二个要求

我看不出有什么理由不能调用这个构造函数。

c++ initialization c++20 stdarray std-span
1个回答
2
投票

限定转换只能使某些东西变得更加 const 限定。

decltype(data(arr))
const int*
代表
const std::array<int, 3>&
const int
无法通过资格转换转换为
int

不过,

std::span<const int>(std::array<int, 3>{})
确实有效(
const int
->
const int
)。

© www.soinside.com 2019 - 2024. All rights reserved.