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;
}
foreach (i, member; __traits(allMembers, lst)) {
lstmap[cast(int) __traits(getMember, lst, member)] = member;
}
(copied from question as community wiki)
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With