How to insert code in place with templates/mixins?

rumbu rumbu at rumbu.ro
Mon Dec 20 09:30:30 UTC 2021


On Monday, 20 December 2021 at 08:45:50 UTC, rempas wrote:
> Here I am having a problem with templates again. No matter how 
> much I read, I can't seem to understand how templates/mixins 
> work.
>
> So any ideas why this doesn't work?

because you cannot have statements directly in a template (the 
fact that is a mixin template is irelevant), only declarations.

If you want to just insert some random code, use strings. You can 
create a templated enum to store your parametrized string. Please 
note how your parameter (c) becomes part of the resulting string 
through concatenation (~):

```
enum add_char(char c) =

   `if (stdout_index < STDOUT_BUF_LEN) {
     stdout_buffer[stdout_index++] =` ~ c ~ `;
     continue;
   } else {
     sys_write(1, stdout_buffer.ptr, cast(i32)stdout_index);
     stdout_index = 0;
     stdout_buffer[stdout_index++] =` ~ c ~ `;
     continue;
   }`;

```

and when you want the code inserted:

```
mixin(add_char!'%');
```

If you want to be sure that your string is syntactically correct, 
use token strings (https://dlang.org/spec/lex.html#token_strings)




More information about the Digitalmars-d-learn mailing list