“std::dynamic_extent” 在 std::span 中的目的是什么?

huangapple go评论75阅读模式
英文:

What's the purpose of std::dynamic_extent in std::span

问题

我知道 std::span 是静态的。它只是一种查看一堆向量/数组等元素的视图。

我看到了 构造函数 中,似乎在第4-6个中使用了 std::dynamic_extent。但在这些构造函数中,还需要一个模板参数来表示大小 - std::size_t N。对我来说,这意味着大小/计数/长度在编译时已知。那么 std::dynamic_extent 到底是什么呢?

英文:

I know std::span is static. It is just view over bunch of vector/array/etc. elements.

I see constructors of span, and it seems like std::dynamic_extent is used in 4-6. But in those constructors, there is a required template parameter for the size - std::size_t N. To me this means that the size/count/len is known at compile time. So what really is std::dynamic_extent?

答案1

得分: 4

std::dynamic_extent 的定义是:

inline constexpr std::size_t dynamic_extent 
    = std::numeric_limits<std::size_t>::max();

它是一个 std::size_t 的特殊值,用于指示 std::span 具有动态范围。

大小需要的模板参数为 std::size_t N。对我来说,这意味着大小/计数/长度在编译时已知。

std::span 的“大小”仍然在编译时指定,只是当“大小”取特殊值时,它被视为动态范围。

英文:

The definition of is std::dynamic_extent is

inline constexpr std::size_t dynamic_extent 
    = std::numeric_limits&lt;std::size_t&gt;::max();

It's a special value of a std::size_t that's used to indicate that the std::span has a dynamic extent.

> There is a required template argument for the size - std::size_t N. To me this means that the size/count/len is known at compile time.

The "size" of the std::span is still specified at compile time, it's just that when the "size" takes on that special value, it's treated as a dynamic extent.

答案2

得分: 0

构造函数会设置初始大小,但当 span 具有 dynamic_extent 时,其大小可能会发生变化。

std::array<int, 4> arr{1, 2, 3, 4};
std::span<int> s{arr}; // 整个数组视图     // 大小为 4
s = s.subspan(1, 2)}; // 限制的数组视图 // 现在大小为 2
英文:

The constructor would set the initial size, but when span has dynamic_extent, its size might evolve

std::array&lt;int, 4&gt; arr{1, 2, 3, 4};
std::span&lt;int&gt; s{arr}; // whole array view     // size is 4
s = s.subspan(1, 2)}; // restricted array view // size is 2 now

huangapple
  • 本文由 发表于 2023年8月5日 06:27:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839400.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定