Mixin operator 'if' directly

Michelle Long HappyDance321 at gmail.com
Sat Dec 22 00:18:30 UTC 2018


On Thursday, 20 December 2018 at 16:23:39 UTC, H. S. Teoh wrote:
> On Thu, Dec 20, 2018 at 11:04:19AM +0000, bauss via 
> Digitalmars-d-learn wrote:
>> On Wednesday, 19 December 2018 at 15:40:50 UTC, Neia Neutuladh 
>> wrote:
> [...]
>> > mixin template foo()
>> > {
>> >   int _ignoreme()
>> >   {
>> >     if (readln.strip == "abort") throw new AbortException;
>> >     return 1;
>> >   }
>> >   int _alsoIgnoreMe = _ignoreme();
>> > }
>> > void main()
>> > {
>> >   mixin foo;
>> > }
>> 
>> That's a genius hack.
>> 
>> I have to adapt this!
>
> Me too!  This is awesome!  This basically lets you insert 
> arbitrary code via mixin templates with essentially no 
> restrictions!  You can even reuse the same ignore-identifiers 
> in multiple instantiations of the same template, e.g.:
>
> 	import std.stdio;
> 	mixin template CodeMixin(int i)
> 	{
> 	    int _impl()
> 	    {
> 		static if (i == 0)
> 		{
> 		    writeln("Haha, we inserted code via declarations!");
> 		    return int.init;
> 		}
> 		else static if (i == 1)
> 		{
> 		    writeln("Well whaddya know, we can do multiple mixins!");
> 		    return int.init;
> 		}
> 		else static assert(0);
> 	    }
> 	    int _impl2 = _impl();
> 	}
> 	void main()
> 	{
> 	    writeln("Does it respect order?");
> 	    mixin CodeMixin!0;
> 	    writeln("I should think so! But you never know...");
> 	    mixin CodeMixin!1;
> 	    writeln("Wow, can we really do multiple mixins of this 
> sort?");
> 	}
>
> The output is:
>
> 	Does it respect order?
> 	Haha, we inserted code via declarations!
> 	I should think so! But you never know...
> 	Well whaddya know, we can do multiple mixins!
> 	Wow, can we really do multiple mixins of this sort?
>
>
> T

Note that it even captures locals:

import std.stdio, std.conv;
mixin template CodeMixin(int i)
{
	int _impl()
	{
		static if (i == 0)
		{
		    writeln("Haha, we inserted code via declarations! - " ~ 
to!string(x));
		    return int.init;
		}
		else static if (i == 1)
		{
		    writeln("Well whaddya know, we can do multiple mixins! - " 
~ to!string(x));
		    return int.init;
		}
		else static assert(0);
	}
	int _impl2 = _impl();
}
void main()
{
	int x = 3;
	writeln("Does it respect order?");
	mixin CodeMixin!0;
	writeln("I should think so! But you never know...");
	x = 4;
	mixin CodeMixin!1;
	writeln("Wow, can we really do multiple mixins of this sort?");
	getchar();
}


Seems like it could be used to replace a lot of string mixins so 
that real debugging could take place along with CT error 
checking, etc.






More information about the Digitalmars-d-learn mailing list