iterate over enum name:value pairs

bearophile bearophileHUGS at lycos.com
Sat Dec 7 08:50:42 PST 2013


Jay Norwood:

> In Ali Çehreli very nice book there is this example of 
> iterating over enum range which, as he notes, fails
>
> http://ddili.org/ders/d.en/enum.html
>
>   enum Suit { spades, hearts, diamonds, clubs }
>
>     foreach (suit; Suit.min .. Suit.max) {
>         writefln("%s: %d", suit, suit);
>     }
>
> spades: 0
> hearts: 1
> diamonds: 2
>                ← clubs is missing
>
>
> It seems like there is interest in iterating over the 
> name:value pairs of an enum.  Is this is already available with 
> some D programming trick?

min and max of enumeratinos are traps, I don't use them.

enum Suit { spades = -10, hearts = 10 }

Here max and min are worse than useless to list the enumeration 
members.


Also don't define "max" and "min" as members of the enumeration, 
because this causes a silent silly name clash:

enum Suit { spades, hearts, max, min, diamonds, clubs }


This is how you usually iterate them:


void main() {
     import std.stdio, std.traits;
     enum Suit { spades, hearts, diamonds, clubs }

     foreach (immutable suit; [EnumMembers!Suit])
         writefln("%s: %d", suit, suit);
}


But keep in mind that too has a trap:


void main() {
     import std.stdio, std.traits;
     enum Suit { spades = 0, hearts = 1, diamonds = 1, clubs = 2 }

     foreach (immutable suit; [EnumMembers!Suit])
         writefln("%s: %d", suit, suit);
}

Prints:

spades: 0
hearts: 1
hearts: 1
clubs: 2


There are cases where the supposed "strong typing" of D is a joke 
:-) Try to do the same things with Ada enumerations.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list