Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reflection

d

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;
}
like image 796
Aftershock Avatar asked Jul 23 '11 07:07

Aftershock


2 Answers

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

(copied from question as community wiki)

like image 161
2 revs, 2 users 89% Avatar answered Nov 11 '22 14:11

2 revs, 2 users 89%


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".

like image 23
toriningen Avatar answered Nov 11 '22 15:11

toriningen