Is this range behaviour correct?

Jonathan M Davis jmdavisProg at gmx.com
Thu Mar 14 03:46:18 PDT 2013


On Thursday, March 14, 2013 11:08:52 Andrea Fontana wrote:
> I'm trying to implement a db cursor as simple InputRange. I can't
> implement as forward range because using c-api I can't clone/save
> cursor.
> 
> I wrote popFront() front() and empty() method and my range works
> fine.
> 
> Using on a foreach() it browses all elements inside range until
> range is exausthed.
> 
> If i do another foreach() it doesn't restart (empty() is called
> and it returns true, of course).
> 
> Is it the correct behaviour of a inputrange or have i missed
> something?

foreach(e; range)
{
}

translates to something like

for(auto _range = range; !_range.empty; _range.popFront())
{
    auto e = _range.front;
}

That means that foreach will alter the original range unless it's a struct 
which implicitly saves via =. Pure input ranges can't be saved, and therefore 
if you iterate over one until it's empty, it's empty, and it won't magically 
have elements again if you use foreach on it again.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list