EnumMemberNames

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Nov 27 06:38:51 PST 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.


More information about the Digitalmars-d-learn mailing list