foreach with enum

Robert Fraser fraserofthenight at gmail.com
Thu Jul 19 23:00:25 PDT 2007


Thomas Mader Wrote:

> I am just porting some of my little Java programs to D to get comfortable with the langugage and realized that I cannot use foreach with Enums.
> In Java I can do:
> enum Color { Kreuz, Pik, Herz, Karo }
> for(Color color : Color.values()) {}
> 
> AFAIK thats not possible in D yet.

Hi Thomas,

D enums are effectively just collections of integral constants, optionally with a namespace. Java enums are a lot more powerful (though I think they go a little bit overboard -- if you're adding methods to your enum members, isn't it about time you made them a true class hierarchy?).

I created a mixinable template generating an enum-like struct that overcomes many of the shortcomings of D's enum (there's a "toString" method to get the name, a "members" static method to get a collection of all the members (so you can loop through them just fine), and it's possible to check if a particular member exists by using an is expression). I've also created a "BitSwitch" template that's a bit harder to work with, but with the same advantages. They're just structs with a single uint member, so they're no less efficient than enums are now.

I can post both of them if you want, but others have probably come up with (better) implementations (I think someone on learn mentioned they hand done something similar).



More information about the Digitalmars-d mailing list