简体   繁体   中英

Why are C++ 20 range algorithms in <algorithm> and views in <ranges>?

I admit this is nitpicking about naming but beside my nitpicking about naming I have a bit of a real life code review experience where I have seen people include <ranges> when they only need <algorithm> eg when using std::ranges::count_if .

So why put range algorithms in <algorithm> and views in <ranges> ? It would make more sense to me to either:

  • put range algorithms in <algorithm> and rename <ranges> to <views> / <range_views>
  • put both range algorithm and views in <ranges>

note: I know I am oversimplifying the distinction between headers, <ranges> also contains a lot of concepts and building blocks , so it is possible that is part of the justification.

I am not the author of the proposals, so I cannot canonically answer why the choice was made. At best, I can suggest reasons why the choice makes sense.

The One Ranges Proposal P0896R4 doesn't seem to have rationale for the choice. Range Adaptors and Utilities P0789R3 did not have these algorithms.

So why put range algorithms in <algorithm>

The clue is in the name :) They are algorithms, and algorithms can be found in this header.

If someone is looking for find_if , they can find both the iterator algorithm and the range algorithm in the same place.

So why put range [...] views in <ranges> ?

There used to not be views in any of the existing headers, so using the existing ones might not have been appropriate. Hence a new header was introduced.

There was an analogue for subset of views, namely range adaptor views. There were (and still are) iterator adaptors. Those are defined in <iterator> . I don't think that would have been a good place to put range adaptors.

put range algorithms in <algorithm> and rename to <views> / <range_views>

But <ranges> contains more than just views. It contains concepts such as ranges::range , range primitive classes such as ranges::sentinel_t , range specific iterators such as ranges::borrowed_iterator_t , functions that are analogous to iterator facilities such as std::ranges::begin . Naming the header <views> might have been misleading.

put both range algorithm and views in <ranges>

Perhaps if the iterator algorithms had originally been placed in <iterator> , then range algorithms would have been placed in <ranges> to follow that convention. But as it is, the previous convention was to split the algorithms into a separate header, and that convention was followed with ranges.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM