Why does this mixin fail to compile?

Steven Schveighoffer schveiguy at gmail.com
Wed Jul 3 03:52:41 UTC 2024


On Tuesday, 2 July 2024 at 07:23:42 UTC, ryuukk_ wrote:

> I said it 2 times already, i don't want string concatenation, 
> i'll benchmark later, but not right now, right now i'm looking 
> for a functioning code without string concatenation

Your buffer solution works, but you need to put it inside a 
*function*, not at declaration scope. What you wrote declares 
*runtime* variables, which wouldn't be usable at compile time (if 
you got it past the parser, which is where it was failing).

So for instance:

```d
mixin template implement()
{
     mixin(() {
         // ctfe new array is basically the same as static array
         char[] buffer = new char[4096];
         int pos = 0;

         void append(string str)
         {
             buffer[pos .. pos + str.length] = str[];
             pos += str.length;
         }

         append("void* ctx;");
         return buffer[0 .. pos];
     }());
}
```

And yes, it is faster to do this than appending. But you have to 
do a *lot* of it to make a huge difference.

-Steve


More information about the Digitalmars-d-learn mailing list