Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the C++20 range library have its own namespace?

Why is std::range::sort (and other range-based algorithms) implemented in the range namespace? Why isn't it defined as an overload of std::sort taking a range?

like image 379
Touloudou Avatar asked Oct 24 '20 21:10

Touloudou


Video Answer


1 Answers

It's to avoid disrupting existing code bases. Eric Niebler, Sean Parent and Andrew Sutton discussed different approaches in their design paper D4128.

3.3.6 Algorithm Return Types are Changed to Accommodate Sentinels

... In similar fashion, most algorithm get new return types when they are generalized to support sentinels. This is a source-breaking change in many cases. In some cases, like for_each, the change is unlikely to be very disruptive. In other cases it may be more so. Merely accepting the breakage is clearly not acceptable. We can imagine three ways to mitigate the problem:

  1. Only change the return type when the types of the iterator and the sentinel differ. This leads to a slightly more complicated interface that may confuse users. It also greatly complicates generic code, which would need metaprogramming logic just to use the result of calling some algorithms. For this reason, this possibility is not explored here.

  2. Make the new return type of the algorithms implicitly convertible to the old return type. Consider copy, which currently returns the ending position of the output iterator. When changed to accommodate sentinels, the return type would be changed to something like pair<I, O>; that is, a pair of the input and output iterators. Instead of returning a pair, we could return a kind of pair that is implicitly convertible to its second argument. This avoids breakage in some, but not all, scenarios. This subterfuge is unlikely to go completely unnoticed.

  3. Deliver the new standard library in a separate namespace that users must opt into. In that case, no code is broken until the user explicitly ports their code. The user would have to accommodate the changed return types then. An automated upgrade tool similar to clang modernize can greatly help here.

We, the authors, prefer (3).

Ultimately, it was to be the least disruptive to existing code bases that move onto building using C++20 enabled compilers. It's the approach they themselves preferred, and seems like the rest is history.

like image 52
StoryTeller - Unslander Monica Avatar answered Sep 18 '22 12:09

StoryTeller - Unslander Monica