Ranges and/versus iterators

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Mar 23 13:34:24 PDT 2010


On 03/23/2010 02:45 PM, Fawzi Mohamed wrote:
> Andrei, as the topic just came up a comment on the range interface.
> Just for plain forward iterators iterators having
>
> bool empty()
> E front()
> void popFront()
>
> makes the interface non reentrant.
> For that purpose having a single function is better.
> I use
>
> bool popFront(ref T t)
> // returns true if there is a next element, and in that case returns it
> in t
>
> this can be used by several consumers concurrently without problems and
> creating filters, combiners,... is simple.
> Another advantage is that a single object can implement several iterators.
> A disadvantage is that even if there is a single iterator D makes type
> inference cumbersome, i.e. you cannot simply use auto, as in a loop you
> have to declare the variable before using it as the loop is
> T a;
> while (it.popFront(a)){
> //...
> }

We've discussed this extensively, and I lost sleep over this simple 
matter more than once. The main problem with bool popFront(ref E) is 
that it doesn't work meaningfully for containers that expose references 
to their elements.

The interface with front() leaves it to the range to return E or ref E.

An alternative is this:

bool empty();
ref E getNext(); // ref or no ref

I'm thinking seriously of defining input ranges that way. The underlying 
notion is that you always move forward - getting an element is 
simultaneous with moving to the next.


Andrei



More information about the Digitalmars-d mailing list