iterate over enum name:value pairs

Jay Norwood jayn at prismnet.com
Sun Dec 8 17:37:35 PST 2013


It looks like the writeln() does a pretty good job, even for enum 
names.

I also saw a prettyprint example that prints the structure member 
name, and compared its output.
http://forum.dlang.org/thread/ip23ld$93u$1@digitalmars.com


module main;

import std.stdio;
import std.traits;

void main()
{
     enum Suit { spades, hearts=4, diamonds=10, clubs }
     enum SuitShort { spd, hrt=4, dmd=10, clb }

     static struct Suits { Suit nm; int val; int val2;  SuitShort 
shortNm;}

     static Suits[] suits =  [
		{Suit.spades, 1, 6, SuitShort.spd},
		{Suit.hearts, 4, 10, SuitShort.hrt},
		{Suit.diamonds, 4, 10, SuitShort.dmd},
		{Suit.clubs, 10, 16, SuitShort.clb}
	];

     foreach (immutable member;  suits)
     {
	auto fields = __traits(allMembers, typeof(member));
	auto values = member.tupleof;

	foreach (index, value; values)
	{
	    writef("%s=%s, ", fields[index], value);
	}
	writeln();
  	member.writeln();
     }
}


output:
nm=spades, val=1, val2=6, shortNm=spd,
immutable(Suits)(spades, 1, 6, spd)
nm=hearts, val=4, val2=10, shortNm=hrt,
immutable(Suits)(hearts, 4, 10, hrt)
nm=diamonds, val=4, val2=10, shortNm=dmd,
immutable(Suits)(diamonds, 4, 10, dmd)
nm=clubs, val=10, val2=16, shortNm=clb,
immutable(Suits)(clubs, 10, 16, clb)


More information about the Digitalmars-d-learn mailing list