Mixin helper help

Hipreme msnmancini at hotmail.com
Thu Jan 12 11:34: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 template` cannot be used like that. The only statement it 
accepts are declaration statements: Look at 
https://dlang.org/spec/module.html#MixinDeclaration

It says it must compile to a valid DeclDef, which means you can't 
put code like that.



Mixin templates are used only for declaring new variables, types 
and functions, it can't simply put call statements like that. You 
could do this by simply calling a function such as:

```d
void helper()
{
     writeln(12);
}
```

I think you'll need to comment more on your problem if you wish 
specialized help


More information about the Digitalmars-d-learn mailing list