generating switch case from compile time sequence of functions

Adam D. Ruppe destructionator at gmail.com
Sun Jul 14 19:59:36 UTC 2019


On Sunday, 14 July 2019 at 19:26:41 UTC, Sjoerd Nijboer wrote:
> The code it must generate for `doSwitch!(foo, bar)()` is
> `{
>     switch (int)
>     {
>         foo:
>             foo();
>             return;
>         bar:
>             bar();
>             return;
>     }
> }`
>

I'd probably just do

void doSwitch(items...)(int i) {
    switch(i) {
       static foreach(idx, item; items) {
          case idx:
              item();
              return;
       }
    }
}


That should work pretty simply.

>     enum temp = [FunctionNames].join(", ");
>
>     enum switchEnum = "{" ~ temp ~ "};";

Were you trying to do a mixin here? The error you mention below 
is trying to use this switchEnum thing as a type... and it isn't 
a type, it is just a string. the mixin() is necessary to compile 
it into code and thus create that type.

mixin("enum switchEnum = { " ~ temp ~ "}");

but I think even attempting this is overcomplicating.

>         static foreach (name; FunctionNames)
>         {
>             name ~ " : " ~ name ~ "(); break;";
>         }

ditto down here too.


More information about the Digitalmars-d-learn mailing list