Emulation macros and pattern matching on D

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 5 07:31:18 PDT 2015


On Friday, 5 June 2015 at 14:15:09 UTC, Dennis Ritchie wrote:
> For example, why here I can simply write:
>
> void main() {
>     int b = 5;
>     mixin(`int a = b;`);
>     assert(a == 5);
> }
>

This becomes:
     int b = 5;
     int a = b;
     assert(a == 5);

> Why should not I write like this:
>
> void main() {
>     int b = 5;
>     mixin(`"int a = " ` ~ b ~ ` ";"`);
>     assert(a == 5);
> }

This is a train wreck.

If you want to use `b` in a mixin, it needs to be a compile time 
constant, e.g. an enum.
You can't concatenate an int with strings.
You messed up the quotes. You might be mistaking backticks for 
something special, but they're basically just quotes.

Fixing it to compile:
     import std.conv: to;
     enum int b = 5;
     mixin("int a = " ~ b.to!string ~ ";");
     /* alternatively: mixin(`int a = ` ~ b.to!string ~ `;`); */
     assert(a == 5);

After the mixin this becomes:
     enum int b = 5;
     int a = 5;
     assert(a == 5);

Not that here it's `a = 5;`, whereas above it's `a = b;`.


More information about the Digitalmars-d-learn mailing list