How to define an interator to provide array like behaviour in a class?
Jonathan M Davis
jmdavisProg at gmx.com
Tue Oct 16 15:23:26 PDT 2012
On Wednesday, October 17, 2012 00:03:46 Gary Willoughby wrote:
> I want to do something like this (Collection is a custom type):
>
> Collection x = new Collection();
> x.add(something);
> x.add(somethingElse);
>
> foreach(type value; x)
> {
> writeln(value);
> }
>
> Collection is a class with a private array member variable which
> actually holds the collection data entered via the add method.
> What do i need to add to the Collection class to make it iterable
> (whilst it's actually iterating through the member array) so the
> foreach loop works as expected?
1. Define opApply (see section labeled "Foreach over Structs and Classes with
opApply after here: http://dlang.org/statement.html#foreach_with_ranges)
2. Or make it a range (see http://dlang.org/statement.html#foreach_with_ranges
and http://ddili.org/ders/d.en/ranges.html ), which would probably be a bad
idea, since containers really shouldn't be ranges.
3. Or do what std.container does and overload opSlice which returns a range
over the container (see http://dlang.org/operatoroverloading.html#Slice and
http://dlang.org/phobos/std_container.html in addition to the links in #2).
Overall, this is the best approach.
But regardless of which approach you take, you really should read up on ranges
if you want to be doing much with D's standard library, and
http://ddili.org/ders/d.en/ranges.html is the best tutorial on them at this
point. There's also this recent article by Walter Bright which explains one of
the main rationales behind ranges:
http://www.drdobbs.com/architecture-and-design/component-programming-in-
d/240008321
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list