On Saturday, 30 May 2020 at 22:06:30 UTC, mw wrote:
I want to generate a new symbol (new variable name) from
existing one: e.g. in C:
$ cat t.c
--------------------------------------------
#define f(x) _##x
int main() {
int f(x) = 3;
return _x;
}
$ make t
cc t.c -o t
$ ./t
$ echo $?
3
--------------------------------------------
I wonder how to do this in D? using template / mixin? traits?
Can you show me an example?
Thanks.
enum f(string x) = "_" ~ x;
int main() {
mixin("int ", f!"x", " = 3;");
return _x;
}
This uses a templated [1] manifest constant [2] to generate the
variable name at compile time, and a mixin statement [3] to
insert the definition of `_x` into the program.
[1] https://dlang.org/spec/template.html#variable-template
[2] https://dlang.org/spec/enum.html#manifest_constants
[3] https://dlang.org/spec/statement.html#mixin-statement