Why does std.container.array does not work with foraech( i, a; array ) {} ?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 29 02:07:07 PDT 2016


On Sunday, May 29, 2016 07:14:12 ParticlePeter via Digitalmars-d-learn wrote:
> Which of the op(Index) operators is responsible for enabling this
> kind of syntax?
> Would it be possible to get it work with UFCS or would I have to
> wrap the array?

std.container.array.Array works with foreach via ranges.

foreach(e; myContainer)
{
}

gets lowered to

foreach(e; myContainer[])
{
}

which in turn gets lowered to something like

for(auto r = myContainer[]; !r.empty; r.popFront())
{
    auto e = r.front;
}

Ranges do not support indices with foreach, and that's why you're not able
to get the index with foreach and Array. However, if you use
std.range.lockstep, you can wrap a range to get indices with foreach. e.g.

foreach(i, e; lockstep(myContainer[]))
{
}

http://dlang.org/phobos/std_range.html#.lockstep

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list