Is it possible to get the names and values of the members of an enum in D?

Viewed 238

I would like to get the names and values from an enum type in D2. I know I can get enum values using std.traits but what about the names?

Given:

enum lst
{
  apple,
  bottle,
  orange,
  blue    
}

I would like to get an associative array like.

string lstmap[int] = [1:"apple", 2:"bottle", 3:"orange", 4:"blue"].

The answer is yes. The solution, as someone showed me is:

foreach (i, member; __traits(allMembers, lst)) {
  lstmap[cast(int) __traits(getMember, lst, member)] = member;
}
3 Answers

In case you want this solely for purposes of value-to-string convertation, consider using std.conv.to!string(lst.orange) — will evaluate to "orange".

Related