How to iterate using foreach on a class?

Jonathan M Davis jmdavisProg at gmx.com
Fri Nov 1 04:41:36 PDT 2013


On Friday, November 01, 2013 12:30:10 Gary Willoughby wrote:
> I have a class which contains an array as a core collection of
> data. I want to pass an instance of this class to a foreach loop
> and iterate through the enclosed array. How do i do this? I've
> asked this before and got an answer but i can't find anything now.

In general, if you want to make something work with foreach, you either make 
it a range, or you give it an opSlice which returns a range (another 
alternative would be define opApply, but in general, code should be using the 
range primitives rather than opApply). Given that you're looking to iterate an 
array, and you presumably don't want the array to be consumed when iterating, 
the simplest would be to simply declare an opSlice on the class returns the 
array. e.g.

class C
{
    int[] foo;
    auto opSlice() { return foo; }
}

Then when you use the class in a foreach loop, it'll be sliced, and the return 
value of opSlice (the array in this case) will then be iterated over.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list