foreach with classes like associative array?

Ali Çehreli acehreli at yahoo.com
Fri Jan 20 17:11:51 PST 2012


On 01/20/2012 04:53 PM, Matt Soucy wrote:
> So I was messing around with some code I've been writing today, and I
> wanted to use a foreach for something, as if it were an associative
> array. The problem is, I can't find any information on how to do that.
> I can't use something like "alias this", because the class I'm writing
> acts as a wrapper that lets me use string offsets for something that's
> not string-indexed by default.
> I don't see any sort of opApply or similar to do this, and the foreach
> section of dlang.org doesn't help. Is there a way to do it?
> Thank you,
> -Matt Soucy

I have a chapter for this but it hasn't been translated yet:

   http://ddili.org/ders/d/foreach_opapply.html

Translating from there, when there is the following piece of code:

     // What the programmer wrote:
     foreach (/* loop variables */; object) {
         // ... operations ...
     }

The compiler uses the following behind the scenes:

     // What the compiler uses:
     object.opApply(delegate int(/* loop variables */) {
         // ... operations ...
         return termination_code;
     });

You must terminate your loop if termination_code is non-zero. So all you 
need to do is to write an opApply overload that matches the loop variables:

class C
{
     int[3] keys;
     int[3] values;

     int opApply(int delegate(ref int, ref int) operations) const
     {
         int termination_code;

         for (size_t i = 0; i != keys.length; ++i) {
             termination_code = operations(keys[i], values[i]);
             if (termination_code) {
                 break;
             }
         }

         return termination_code;
     }
}

import std.stdio;

void main()
{
     auto c = new C;

     foreach(key, value; c) {
         writefln("%s:%s", key, value);
     }
}

Ali


More information about the Digitalmars-d-learn mailing list