Ranges and/versus iterators

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Mar 23 16:01:45 PDT 2010


On 03/23/2010 05:41 PM, Fawzi Mohamed wrote:
>
> On 23-mar-10, at 21:34, Andrei Alexandrescu wrote:
>
>> [...]
>> 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.
>
> yes I agree that it is a difficult problem, the single function works
> well in the basic iterator case, but does not generalize well to
> modifiable values.
> In most cases I resorted to returning pointers. The templates that
> generate opApply (still D1.0 ;) from that is smart enough to remove the
> pointer when possible as the ref already gives that.
> Still not perfect, as always there are tradeoffs...
>
>> 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.
>
> already better (for basic iterators), but still not reentrant, if
> another thread executes between empty and getNext...

It can't :o).

> anyway any choice has some drawbacks... I like bool next(ref T) because
> it works well also for streams... and somehow (using T* or not depending
> on the type) can accommodate all iteration needs.
> Not perfectly nice, but workable.

next(ref T) works well _only_ on streams. It works badly on containers.


Andrei



More information about the Digitalmars-d mailing list