How to insert code in place with templates/mixins?

rempas rempas at tutanota.com
Mon Dec 20 10:49:20 UTC 2021


On Monday, 20 December 2021 at 09:30:30 UTC, rumbu wrote:
>
> 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)

Thanks a lot for the info. When I try to use this code, I'm 
getting the following error:

```
Error: expression expected, not `%`
Error: expression expected, not `%`
```

So I suppose there is a problem with string concatenation. I 
couldn't use it anyway because it is inefficient and because I'm 
using betterC. Do you know any other way that I can concatenate 
strings that does not depend an the Garbage Collector or the 
standard library?


More information about the Digitalmars-d-learn mailing list