Why does this mixin fail to compile?

Dennis dkorpel at gmail.com
Mon Jul 1 21:43:02 UTC 2024


On Monday, 1 July 2024 at 13:00:55 UTC, ryuukk_ wrote:
> please stick to what i wrote, i don't want string 
> concatenation, i provide a reduced example from my project, 
> everything should be a single template block, no extra 
> functions other than the append() one

Mixin templates are a declaration scope, not a function scope, so 
they aren't necessarily analyzed top to bottom. This is why 
allowing partial string mixins would be complicated, consider 
this example:

```D
mixin template implement()
{
     mixin("struct " ~ str);

     mixin("{");

     immutable string str = "T";

     mixin("}");
}
```

It's not obvious how this should be compiled, and this is before 
throwing `static if` and `static foreach` in the mix! If you want 
to procedurally build a type in sequential steps, you'll have to 
do that in a function scope.

If your concern is that such a function would add needless code 
generation, you can use an immediately invoked anonymous function 
like so:

```D
mixin template implement(string typeName, string[] members)
{
     mixin(() {
         string result = "struct " ~ typeName ~ " {";
         foreach (name; members)
         {
             result ~= "int " ~ name ~ ";";
         }
         result ~= "}";
         return result;
     } ());
}

mixin implement!("S", ["x", "y", "z"]);

immutable s = S(x: 3, y: 5, z: 7);
```

You can use your fixed size array append function to try and 
improve CTFE performance, but I'd start with straightforward 
concatenation, and see if it's actually too slow. In that case, 
maybe see if you can reduce it to a self-contained example and 
post it on bugzilla as a performance bug.


More information about the Digitalmars-d-learn mailing list