User defined type and foreach

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Nov 16 11:08:49 UTC 2017


On Thursday, November 16, 2017 08:43:17 Tony via Digitalmars-d-learn wrote:
> On Thursday, 16 November 2017 at 08:26:25 UTC, Andrea Fontana
>
> wrote:
> > On Thursday, 16 November 2017 at 08:03:48 UTC, Tony wrote:
> >> I made a stack data type and created an opIndex() so it could
> >> be turned into a dynamic array, and created empty()
> >> (unfortunate name), front() and popFront() methods, which I
> >> read allow it to be used with foreach.
> >>
> >> However, when I use the class with foreach, the opindex gets
> >> called to create a dynamic array, rather than use the
> >> empty(),front(),popFront() routines. I would prefer it use the
> >> three methods, rather than create a dynamic array.
> >
> > You can try to implement opApply().
> > Check:
> > http://ddili.org/ders/d.en/foreach_opapply.html
>
> Thanks. Interesting that that page does not mention the behavior
> I am seeing, which is that foreach over a user-defined datatype
> can be implemented with only a 'T[] opIndex()' method.

What you're seeing is intended for containers. If you implement opIndex or
opSlice with no parameters so that you can slice the object with no indices,
the idea is that it's going to return a range. foreach knows about this so
that you can then iterate over a container with foreach rather than having
to explicitly call a function on the container to get the range to then
iterate over. e.g. with

RedBlackTree rbt;
...

you can do

foreach(e; rbt)
{...}

instead of

foreach(e; rbt[])
{...}

though if you then pass the container to a range-based function, you're
still going to have to explicitly slice it.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list