how to achieve C's Token Pasting (##) Operator to generate variable name in D?

Johannes Loher johannes.loher at fg4f.de
Sun May 31 00:43:20 UTC 2020


On Saturday, 30 May 2020 at 23:39:31 UTC, mw wrote:
> On Saturday, 30 May 2020 at 22:21:14 UTC, Paul Backus wrote:
>> [...]
>
>
> Thank you all for the reply.
>
> I hate to write boilerplate code:
>
> [...]

import std.stdio : writeln;

mixin template f(T, string name, T value = T.init)
{
     mixin("T _" ~ name ~ " = value;");
}

void main()
{
     mixin f!(int, "x", 3);
     _x.writeln; // prints 3
     mixin f!(float, "y", 1.23f);
     _y.writeln; // prints 1.23
     mixin f!(string, "z");
     _z.writeln; // prints an empty string (== string.init)
}



More information about the Digitalmars-d-learn mailing list