code muncher
code muncher

Reputation: 1682

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

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?

Upvotes: 5

Views: 1302

Answers (2)

Brian61354270
Brian61354270

Reputation: 14434

The definition of std::dynamic_extent is

inline constexpr std::size_t dynamic_extent 
    = std::numeric_limits<std::size_t>::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.

Upvotes: 5

Jarod42
Jarod42

Reputation: 218138

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

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

Upvotes: 0

Related Questions