foreach with classes like associative array?

Steven Schveighoffer schveiguy at yahoo.com
Tue Jan 24 16:21:45 PST 2012


On Fri, 20 Jan 2012 19:53:33 -0500, Matt Soucy <msoucy at csh.rit.edu> 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,

 From your question, I'm not sure what you are looking for.  It seems you  
are aware of opApply, but have dismissed it as being usable.

If it helps, here is the reference for how foreach works on various things:

http://www.d-programming-language.org/statement.html#ForeachStatement

Could it be that you want to do this?

class C
{
    int x;
    int y;
}

C c;

foreach(string membername, value; c) {...} // iterate with "x" and "y" as  
membername

???

I think there is a way to do it with tupleof, but I'm not sure if you can  
get the member names during iteration.

-Steve


More information about the Digitalmars-d-learn mailing list