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

Timoses timosesu at gmail.com
Thu Apr 26 16:10:16 UTC 2018


The following should depict what I'm trying to achieve:


```
import std.stdio;

enum menum { A, B, C }

void main()
{
    foo(menum.B);
}

void foo(menum e)
{
     // Not possible!!!!
     // run time variable 'e' in conjunction with template 'Temp'
     writeln(Temp!(GetMenum(e)));
}

static int i = 0;

template Temp(menum e)
{
     // ... do stuff
     shared static this()
     {
         static if (e == menum.A)
             i = 1;
     }

     import std.meta : Alias;
     alias Temp = Alias!i;
}

// Trying to return a compile-time variable with a function... 
Not like this...
// I don't see a way to pass in the run-time variable without a 
function..
template GetMenum()
{
     menum GetMenum(menum e)
     {
         import std.traits : EnumMembers;
         static foreach(mem; EnumMembers!menum)
             if (mem == e)
                 return mem;

         return menum.A;
     }
}
```

yields: Error: variable e cannot be read at compilte time

However, if I replace foo with
```
void foo(menum e)
{
     import std.traits : EnumMembers;
     static foreach(mem; EnumMembers!menum)
         if (mem == e)
             writeln(Temp!(GetMenum(mem)));
}
```
it works..

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?


More information about the Digitalmars-d-learn mailing list