On Wednesday, 21 February 2018 at 22:11:04 UTC, Jean-Louis Leroy
wrote:
Here's what I am trying to do:
mixin template MakeFun(string ID, int X)
{
int mixin(ID)() { return X; }
}
mixin MakeFun!("one", 1); // int one() { return 1; }
Alas I get:
makefunc.d(3): Error: no identifier for declarator `int`
makefunc.d(3): Error: found `{` when expecting `;`
makefunc.d(3): Error: declaration expected, not `return`
makefunc.d(4): Error: unrecognized declaration
Is there a shorter way than building the entire function
definition as a string mixin? As in:
mixin template MakeFun(string ID, int X)
{
import std.format;
mixin(format("int %s() { return %s; }", ID, X));
}
mixin MakeFun!("one", 1);
Mixins have to be full declarations. You can't mix in bits and
pieces... except when you can:
import std.stdio;
void main()
{
enum teste = "asdf";
string s = mixin("teste");
writeln(s); //Prints "asdf"
}
It looks like a grammar error as opposed to a semantic one. D's
grammar just doesn't support `mixin` in the function name
position. One way you can make it a little more palateable:
mixin template MakeFun(string ID, int X)
{
import std.format;
mixin(q{ int %s { return %s; } }.format(ID, X));
}
`q{}` denotes a token string that must contain valid tokens (I'm
not sure if the available compiler implementations actually
enforce this), and I _think_ token strings will be properly
syntax-highlighted by most tools.
https://dlang.org/spec/lex.html#token_strings