如何传递空跨度对象



有没有办法将空的std::span<int>传递给函数?

我有一个功能如下:

bool func( const std::vector<int>& indices )
{
if ( !indices.empty( ) )
{
/* do something */
}
...
}

// when calling it with an empty vector
const bool isAcceptable { func( std::vector<int>( 0 ) ) };

我想把它改为使用std::span而不是std::vector,这样它也可以得到std::array原始数组作为它的参数。

现在这里:

bool func( const std::span<const int> indices )
{
if ( !indices.empty( ) )
{
/* do something */
}
...
}

// when calling it with an empty span
const bool isAcceptable { func( std::span<int>( ) ) }; // Is this valid code?

std::span是否正确支持所有连续容器(例如std::vectorstd::array等(?

std::span的默认构造函数记录为:

constexpr span() noexcept;

构造一个空跨度,其data() == nullptrsize() == 0

因此,传递默认构造的std::span<int>()是定义良好的。在其上调用empty()保证返回true


std::span是否正确支持所有连续容器(例如std::vectorstd::array等(?

基本上,std::span可以由任何模拟连续和大小范围的东西构建:

template<class R>
explicit(extent != std::dynamic_extent)
constexpr span(R&& range);

构造一个跨度,该跨度是范围范围内的视图;所得到的跨度具有CCD_ 19和CCD_。

特别是,std::vector确实满足这些要求。

对于C样式数组和std::array,有一些特殊的构造函数(利用它们的编译时大小(:

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

构造一个跨度,该跨度是阵列arr上的视图;所得到的跨度具有CCD_ 24和CCD_。

最新更新