How do I make my class iterable?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 22 10:09:15 PDT 2015


On 6/22/15 1:03 PM, Assembly wrote:
> On Monday, 22 June 2015 at 16:52:15 UTC, Ali Çehreli wrote:
>> On 06/22/2015 09:37 AM, q66 wrote:
>>
>>> use opApply.
>>
>> Yes. Additionally, an InputRange interface can be used:
>>
>>   http://ddili.org/ders/d.en/foreach_opapply.html
>>
>> Ali
>
> I was reading exaclty this page that.
>
> I've had implmented this method/properties (I remembered how foreach()
> is translated to for() by the compiler using front/popFront() and such):
>
> T front() { return _app.data[index]; }
> T front(int index, T a) { return _app.data[index]; }
>
>
>      void popFront()
>      {
>          index++;
>      }
>
>
> and called like this:
>
> foreach(int i, MyType p; places) {
>
> but I get this error:
>
> Error: cannot infer argument types, expected 1 argument, not 2
>
> to try solve that error I added the overload method:
>
> T front(int index, T a)
>
> but it didn't worked. How do I solve this?

TBH, opApply is much better suited to classes.

But in order to have multiple parameters with foreach by using a range, 
you must return a tuple:

auto front() { import std.typecons: tuple; return tuple(index, 
_app.data[index]);}

Note, do NOT do this on your class, you should be creating a range 
struct type, and return the range from opIndex() with no parameters.

-Steve


More information about the Digitalmars-d-learn mailing list