Template to retrieve compile-time enum member from run-time enum member?

Simen Kjærås simen.kjaras at gmail.com
Thu Apr 26 16:46:11 UTC 2018


On Thursday, 26 April 2018 at 16:10:16 UTC, Timoses wrote:
> Is it possible to use a template to place the "static foreach" 
> looping to find the correct enum value into? Like I am trying 
> in the initial "draft" GetMenum?

As the compiler says, the value of `e` is not known at 
compile-time. In order to correctly instantiate the template with 
that value, all possible instantiations must be instantiated, and 
the correct one chosen by a static foreach, just like you do.

The only step you're missing is the template needs to be 
instantiated inside the static foreach, like this:

auto instantiateWith(alias Fn, T)(T x)
if (is(T == enum))
{
     import std.traits : EnumMembers;
     switch (x)
     {
         static foreach (e; EnumMembers!T)
             case e:
                 return Fn!e;
         default:
             assert(false);
     }
}

enum menum { A, B, C }

template Temp(menum m)
{
     enum Temp = m.stringof;
}

unittest {
     menum m = menum.A;
     import std.stdio;
     assert(instantiateWith!Temp(m) == Temp!(menum.A));
     m = menum.B;
     assert(instantiateWith!Temp(m) == Temp!(menum.B));
     m = menum.C;
     assert(instantiateWith!Temp(m) == Temp!(menum.C));
}

--
   Simen


More information about the Digitalmars-d-learn mailing list