Invalid foreach aggregate

Marc Schütz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Nov 17 04:22:19 PST 2015


On Tuesday, 17 November 2015 at 11:58:22 UTC, Chris wrote:
> I did just that and I could find the culprit. It's opIndex(). 
> It works up until 2.068.0, with 2.068.1 I already get this 
> error:
>
> "primitives.d(7): Error: invalid foreach aggregate 
> doSomething(items).opIndex()"
>
>     @property size_t opIndex()
>     {
>       return cnt;
>     }

Ok, that's a strange implementation of opIndex(). Usually, a 
parameter-less opIndex() is supposed to return a slice into the 
full range, but yours returns a size_t, which of course can't be 
iterated over.

The change that made this stop working is:
https://github.com/D-Programming-Language/dmd/pull/4948

This contains, among others a fix for issue 14625 "opIndex() 
doesn't work on foreach container iteration":
https://issues.dlang.org/show_bug.cgi?id=14625

This allows to iterate directly over containers, without needing 
to slice them first. I guess it's a bit too eager, because if the 
object is already iterable without slicing (as in your example), 
it could just do that. On the other hand, it's a corner case, and 
it might actually be preferable to slice always, if the iterable 
supports it...

In any case, I'd suggest you fix your opIndex(), except if 
there's a really good reason it is as it is.


More information about the Digitalmars-d-learn mailing list