C++ Ranges proposal for the Standard Library
monarch_dodra via Digitalmars-d
digitalmars-d at puremagic.com
Fri Oct 17 07:13:36 PDT 2014
On Friday, 17 October 2014 at 09:17:52 UTC, ZombineDev wrote:
> I saw [this][0] proposal for adding ranges to C++'s standard
> library. The [paper][1] looks at D style ranges, but concludes:
>
>> Since iterators can implement D ranges, but D ranges cannot be
>> used to implement iterators, we conclude that iterators form a
>> more powerful and foundational basis.
>
> What do you guys think?
>
> [0]: https://isocpp.org/blog/2014/10/ranges
> [1]: https://ericniebler.github.io/std/wg21/D4128.html
One problem with C++ style iterators is composition, and their
exponential growth, due to their "pair" approach. Indeed, more
often than not, proper iteration *requires* the "it" *already*
know where the underlying iterator ends. For example, a "stride"
adapter iterator would look like this:
template <typename It>
struct StrideIt
{
It current;
It end;
void operator++()
{
++current;
if (current != end)
++current;
}
}
Then you combine it with:
StrideId<It> sit (it, itend);
StrideId<It> sitend(itend, itend);
for ( ; ++it ; it != itend)
...
As you can see, it quickly becomes bloated and cumbersome. In
particular, it takes *tons* of lines of code, traits and what not
to compose. C++11's "auto" make things somewhat simpler, but it
is still bloated.
Another issue is that iterators model a *pointer* abstraction.
Iterators *must* have "reference_t". ranges are more generic in
the sense that they simply model iteration.
*THAT SAID*, as convenient as ranges are, they do suffer from the
"shrink but can't grow" issue. In particular, you can't really
"cut" a range the way you can with iterators: "first, middle,
last". If you are using RA ranges with slicing, it doesn't show
too much. However, if you are using generic bidir ranges, on
containers such as "DList", you really start to feel the pain.
My personal feeling (IMO):
- Consuming, adapting, producing data: Ranges win hands down.
- Managing, shuffling or inserting elements in a container: To be
honest, I prefer iterators.
Given how C++'s STL is container-centric, whereas D's phobos is
range centric, I can totally understand both sides' position.
More information about the Digitalmars-d
mailing list