Mixin operator 'if' directly

Michelle Long HappyDance321 at gmail.com
Sat Dec 22 07:02:06 UTC 2018


On Saturday, 22 December 2018 at 03:44:09 UTC, Timoses wrote:
> On Wednesday, 19 December 2018 at 15:40:50 UTC, Neia Neutuladh 
> wrote:
>> On Wed, 19 Dec 2018 15:12:14 +0000, bauss wrote:
>> Or while instantiating it:
>>
>> mixin template foo()
>> {
>>   int _ignoreme()
>>   {
>>     if (readln.strip == "abort") throw new AbortException;
>>     return 1;
>>   }
>>   int _alsoIgnoreMe = _ignoreme();
>> }
>> void main()
>> {
>>   mixin foo;
>> }
>
> 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);
>     }

Yep, except they will probably disable it in some way.

Surely though a template could be created that does all the work. 
Just pass an lambda in to a template.

mixin template Code(alias f)
{
	int _impl2 = (() { f(); return int.init; })();
}

mixin Code!(() { writeln("Haha, we inserted code via 
declarations!");});

So now you can do

mixin template foo(bool b)
{
	mixin Code!(() { writeln(b); });
}

If it could be made robust, maybe it would be effective.  One 
still can't insert arbitrary code though. So it is not as useful 
as it looks but still gets over the arbitrary restriction.



More information about the Digitalmars-d-learn mailing list