digitalmars.D.learn - EnumMemberNames
- drug (15/15) Nov 27 2015 I need to get names of enum members, is it possible? EnumMembers returns...
- anonymous (35/50) Nov 27 2015 You have a variety of options with subtle differences:
- Adam D. Ruppe (2/3) Nov 27 2015 pragma(msg, __traits(allMembers, Sqrts));
- drug (2/3) Nov 27 2015 Thanks to all for answers!
I need to get names of enum members, is it possible? EnumMembers returns the members itself, i.e. ``` enum Sqrts : real { one = 1, two = 1.41421, three = 1.73205, } pragma(msg, [EnumMembers!Sqrts]); ``` returns [1.00000L, 1.41421L, 1.73205L] but I need [ "Sqrts.one", "Sqrts.two", "Sqrts.three" ] or [ "one", "two", "three" ]
Nov 27 2015
On 27.11.2015 15:05, drug wrote:I need to get names of enum members, is it possible? EnumMembers returns the members itself, i.e. ``` enum Sqrts : real { one = 1, two = 1.41421, three = 1.73205, } pragma(msg, [EnumMembers!Sqrts]); ``` returns [1.00000L, 1.41421L, 1.73205L] but I need [ "Sqrts.one", "Sqrts.two", "Sqrts.three" ] or [ "one", "two", "three" ]You have a variety of options with subtle differences: ---- module test; import std.algorithm: map; import std.array: array; import std.conv: to; import std.meta: staticMap; import std.range: only; import std.traits: EnumMembers, fullyQualifiedName; enum Sqrts : real { one = 1, two = 1.41421, three = 1.73205, } pragma(msg, only(EnumMembers!Sqrts).map!(to!string).array); /* [['o', 'n', 'e'], ['t', 'w', 'o'], ['t', 'h', 'r', 'e', 'e']] */ enum toString(alias thing) = thing.to!string; pragma(msg, staticMap!(toString, EnumMembers!Sqrts)); /* tuple(['o', 'n', 'e'], ['t', 'w', 'o'], ['t', 'h', 'r', 'e', 'e']) */ pragma(msg, staticMap!(fullyQualifiedName, EnumMembers!Sqrts)); /* tuple("test.Sqrts.one", "test.Sqrts.two", "test.Sqrts.three") */ enum stringOf(alias thing) = thing.stringof; pragma(msg, staticMap!(stringOf, EnumMembers!Sqrts)); /* tuple("one", "two", "three") */ ---- std.conv.to is the first address for conversions between types. I'd say use that unless you have a reason not to. If you're doing code generation, or otherwise need the fully qualified name, use std.traits.fullyQualifiedName. I'm not sure if there would ever be a reason to use .stringof over the other ones, other than some quick debug printing. There are probably more ways I didn't think of.
Nov 27 2015
On Friday, 27 November 2015 at 14:05:46 UTC, drug wrote:pragma(msg, [EnumMembers!Sqrts]);pragma(msg, __traits(allMembers, Sqrts));
Nov 27 2015
On 27.11.2015 17:49, Adam D. Ruppe wrote:__traits(allMembers, Sqrts)Thanks to all for answers!
Nov 27 2015