Mixin operator 'if' directly

Basile B. b2.temp at gmx.com
Sat Dec 22 16:45:54 UTC 2018


On Saturday, 22 December 2018 at 10:11:23 UTC, bauss wrote:
> On Saturday, 22 December 2018 at 03:44:09 UTC, Timoses wrote:
>>
>> Awesome hack!
>> Being a hack, it would be even nicer if it worked ouf of the 
>> box:
>>
>>     mixin template foo(bool b)
>>     {
>>         int _impl() { writeln(b); return int.init; }
>>         int _ipml2 = _impl();
>>     }
>>
>> vs
>>
>>     mixin template foo(bool b)
>>     {
>>         writeln(b);
>>     }
>
> I think this is the closest we can come to it:
>
> mixin template Execute(alias p)
> {
>     auto __execute__()
>     {
>         p();
>
>         return 0;
>     }
>     auto __unused__ = __execute__();
> }
>
> mixin template MyTemplate(int a)
> {
>     mixin Execute!({
>         import std.stdio : writeln;
>         writeln(a);
>     });
> }
>
> void main()
> {
>     mixin MyTemplate!10;
> }

One more line can be saved using a lambda to wrap the alias:

     template ExpressionStatement(alias p)
     {
         const __unused__ = {p(); return 0;}();
     }

Also i prefer the name `ExpressionStatement` to `Execute` because 
this describes exactly what the template does and define its 
limits at the same time.

And congrats to Neia Neutuladh for this find.


More information about the Digitalmars-d-learn mailing list