Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a "range" and a "view" in the rangesv3 ts?

Tags:

c++

range-v3

What's the difference between a "range" and a "view" in the rangesv3 ts?

Don't find any similar answers on G search. Guess I'm struggling with a basic overview of what each one is supposed to do:

is it the case (in c++ speak) that range 'is-a' view, or vice-versa?

Is it simply that a view is read-only range? Or perhaps that the "elements" in the range (what you get when you dereference the iterator) are const in one and not in the other?

Thanks!

like image 989
r webby Avatar asked Dec 24 '22 09:12

r webby


1 Answers

From the docs, a range is:

A range can be loosely thought of a pair of iterators, although they need not be implemented that way.

and:

A view is a lightweight wrapper that presents a view of an underlying sequence of elements in some custom way without mutating or copying it. Views are cheap to create and copy, and have non-owning reference semantics.

A view is a range, just with more restrictions.

More formalized definitions in the TS are in the Range and View concepts. Basically, a range is something that's iterable over, and a view is a range that is semiregular and has constant time copy/move/assignment/begin/end/...

For instance, std::vector<char>, std::string, and std::string_view are all ranges, but only the last one is also a view.


While in the Ranges TS, a View was always semiregular, this restriction was relaxed in P1456. In C++20, a View is instead required to be only default constructible and movable. The additional semantic constraints (all the operations being constant time) still hold. Notably: while a View need not be copyable, if it is copyable, then those copying operations still need to take constant time.

The default construction restriction was lifted in P2325 and other requirements were further relaxed in P2415.

like image 190
Barry Avatar answered Dec 25 '22 22:12

Barry