Can somebody explain why std::span
is introduced? I personally feel std::ranges::views
provides similar functionality like that of std::span
(std::span
is like a subset of std::ranges::views
in terms of functionality).
Asked
Active
Viewed 52 times
0

Harry
- 2,177
- 1
- 19
- 33
-
4`std::ranges::view` is a _concept_. `std::span` is a _class template_ (i.e. specializations are actual types). I don't see how you can consider one a subset of or a substitute for the other. – user17732522 May 20 '22 at 06:47
-
@user17732522 If I'm not wrong I can use either of these to iterate over a container which stores elements in contiguous manner. If that's the case why std::span? – Harry May 20 '22 at 06:54
-
1`std::ranges::view` is a concept. You can only use it to constrain what kind of types (e.g. a `std::span` specialization) a template accepts as template arguments. It is not actually a type you can use to iterate over anything. So I have no idea what kind of use case you have in mind. – user17732522 May 20 '22 at 06:56
-
@user17732522 Sorry I mistook `std::ranges::views` to `std::ranges::view` which I was referring from here https://stackoverflow.com/questions/70387136/iterating-over-first-n-elements-of-a-container-stdspan-vs-viewstake-vs-ran – Harry May 20 '22 at 07:05
-
`std::ranges::views` is a namespace with a collection of view adaptors. I guess you are mainly talking about `take`, `drop` and/or `counted`, but maybe also `ranges::subrange`, which (potentially combined) can be used to create a view into a subrange of any other range (whether contiguous or not). – user17732522 May 20 '22 at 07:09
-
One reason for std::span is that it was introduced years before std::ranges was proposed. Span just missed the train for C++17, so was accepted early for C++20. Once accepted, it is unusual to get unaccepted. – BoP May 20 '22 at 07:16
-
@user17732522 you're correct, so in that case why both are required? – Harry May 20 '22 at 07:18
-
1They type of the adaptors depends on the type of the original range. `std::span` allows referring to a contiguous range without having to refer to the type of the parent range. So you need it e.g. if you want to specify a non-templated function taking a contiguous range. Although, as mentioned in the linked duplicate `std::ranges::take` and others now do the right thing and return a `std::span` where appropriate instead. – user17732522 May 20 '22 at 07:23
-
@BoP [Ranges in no way replace `span`](https://brevzin.github.io/c++/2018/12/03/span-best-span/) – Barry May 20 '22 at 13:57