Mixin helper help

bauss jacobbauss at gmail.com
Fri Jan 13 08:48:49 UTC 2023


On Thursday, 12 January 2023 at 08:03:34 UTC, John Chapman wrote:
> I'm obviously doing something wrong, but don't quite understand.
>
> ```d
> mixin template helper() {
>   mixin("writeln(12);");
> }
>
> struct Foo {
>   void opDispatch(string name)() {
>     import std.stdio;
>     mixin helper!();
>     //mixin("writeln(12);");
>   }
> }
>
> void main() {
>   Foo.init.opDispatch!"bar"();
> }
> ```
>
> The compiler emits these errors about the mixin 
> ("writeln(12);"):
> unexpected `(` in declarator
> basic type expected, not `12`
> found `12` when expecting `)`
> no identifier for declarator `writeln(_error_)`
> semicolon expected following function declaration
> declaration expected, not `)`
>
> Why does the commented code work but the mixin not? Thanks for 
> any pointers.

Mixin templates cannot have statements directly, so you need two 
changes for your code to work:

1. Change your mixin template to something like this:

```d
mixin template helper() {
     // we place the statements in this function instead
     void helper() {
         mixin("writeln(12);");
     }
}
```

2. Change the place where you instantiate to this:

```d
struct Foo {
   void opDispatch(string name)() {
     import std.stdio;
     mixin helper!();
     helper(); // calling the function in the mixin template
   }
}
```


More information about the Digitalmars-d-learn mailing list