How to iterate using foreach on a class?
Nicolas Sicard
dransic at gmail.com
Sun Nov 3 05:28:13 PST 2013
On Friday, 1 November 2013 at 12:37:20 UTC, simendsjo wrote:
> On Friday, 1 November 2013 at 11:41:52 UTC, Jonathan M Davis
> wrote:
>> 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
>
> So we basically have 4 ways..?
> 1) popFront + front
> 2) opSlice
> 3) alias this
> 4) opApply
How about having a nested struct implementing a range interface +
a method (@property) returning it + alias this on the property?
http://dpaste.dzfl.pl/230061d2
More information about the Digitalmars-d-learn
mailing list