Generating switch at Compile Time

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Apr 13 14:33:28 PDT 2017


On 04/13/2017 11:06 PM, Jesse Phillips wrote:
> ---------------------
[...]
>     private static immutable list = AliasSeq!(
>             tuple("a", "q"),
>             tuple("b", "r"),
>             );
[...]
>         switch(search) {
> --->        foreach(li; list) { // li initialization is skipped
>                 mixin("case li[0]:");
>                 mixin("writeln(li[1]);");
>                 return;
>             }
>             default:
>             break;
>         }
[...]
>     }
> ---------------------
>
> Thoughts?

That's not a static foreach. It's a normal run-time foreach. The switch 
jumps into the loop body without the loop head ever executing. The 
compiler is correct when it says that initialization of li is being skipped.

Make `list` an enum or alias instead. Then the foreach is unrolled at 
compile time, you don't get a deprecation message, and it works correctly.

By the way, in my opinion, `case li[0]:` shouldn't compile with the 
static immutable `list`. `list` and `li[0]` are dynamic values. The 
compiler only attempts (and succeeds) to evaluate them at compile time 
because they're typed as immutable. The way I see it, that only makes 
things more confusing.


More information about the Digitalmars-d-learn mailing list