Get enum value name as string at compile time?

Simen Kjærås simen.kjaras at gmail.com
Mon Sep 14 06:25:52 UTC 2020


On Monday, 14 September 2020 at 03:48:51 UTC, Steven 
Schveighoffer wrote:
> Consider the enum:
>
> enum Foo { a, b }
>
> Foo.a.stringof => "a"
> enum x = Foo.a;
> x.stringof => "cast(Foo)0"
>
> Is there another way I can take an enum value that's known at 
> compile time (but not the actual identifier), and get the name 
> of it? I know I can use a switch, or to!string. But I was 
> hoping this was easy for the compiler to figure out some way 
> without involving CTFE.

It is a bit weird that x.stringof doesn't simply return the name 
like Foo.a.stringof does. Anyways, this works:

template enumName(alias a) {
     import std.meta : staticIndexOf, staticMap;

     alias T = typeof(a);
     enum getValue(string name) = __traits(getMember, T, name);
     alias enumValues = staticMap!(getValue, __traits(allMembers, 
T));

     enum enumName = __traits(allMembers, T)[staticIndexOf!(a, 
enumValues)];
}

enum Foo { a = 2, b = 19 }

enum x = Foo.a;
pragma(msg, enumName!x); // "a"

--
   Simen


More information about the Digitalmars-d-learn mailing list