Ranges and indexes with foreach

Jonathan M Davis jmdavisProg at gmx.com
Mon Jan 23 15:44:23 PST 2012


The lack of indexing for foreach and ranges is a bit of problem (not a huge 
one but definitely an annoying one - it's one of the few reasons to still use 
opApply instead of ranges). The obvious solution is to just have the compiler 
provide a counter. So,

foreach(i, e; range)
{
 //code
}

gets lowered to something like

foreach(size_t i = 0; !range.empty; ++i, range.popFront())
{
 auto e = range.front;
 //code
}

But as I understand it, some have been opposed to that idea due to ranges 
which might have more exotic iteration schemes. If that's the case, would it 
make sense to do the above but then allow for ranges which returned their next 
index from popFront? i.e.

foreach(size_t i = 0; !range.empty; i = range.popFront())
{
 auto e = range.front;
 //code
}

So, in the rare cases where a more control of the iteration scheme is 
desirable, instead of being void, popFront would return size_t where that 
size_t is the next index. Is there a reason why this wouldn't do the trick?

I think that we'd definitely benefit by allowing the first case regardless, but 
if the second solves the problem of the index not being flexible enough, then 
presumably that would make this solution for indexing with ranges more 
acceptable.

Thoughts? Is there anything obvious (or non-obvious) that I'm missing here?

- Jonathan M Davis


More information about the Digitalmars-d mailing list