Template mixins - why only declarations

Steve Teale steve.teale at britseyeview.com
Fri Mar 7 02:48:33 PST 2014


On Thursday, 6 March 2014 at 18:36:12 UTC, Dejan Lekic wrote:
>
> Template mixins can't contain statements, only declarations, 
> because they
> (template mixins) are a way to inject code into the context.
>
> Therefore it makes sense to forbid statements, as they can't 
> appear in ANY
> context.

If I side-step slightly, the compiler does not appear to have 
difficulty coping:

import std.stdio;
import std.conv;

string codeString(string A, string B, int I)()
{
    enum n = I*3;
    return "writeln(\""~A~"\"); writeln(\""~B~"\"); 
writefln(\"%d\","~to!string(n)~");";
}

void foo()
{
    mixin(codeString!("One", "Two", 1)());
    writeln("Hello world");
}

void main()
{
    foo();
}




More information about the Digitalmars-d-learn mailing list