static foreach and function generation
Jean-Louis Leroy
jl at leroy.nyc
Mon Jul 23 17:05:09 UTC 2018
Consider:
module genfun;
import std.stdio, std.format, std.traits;
void foo(int a) { writeln("foo(%s)".format(a)); }
void foo(int a, int b) { writeln("foo(%s, %s)".format(a, b)); }
static foreach (fun; __traits(allMembers, genfun)) {
static if (fun == "foo") {
static if (is(typeof(__traits(getOverloads, genfun, fun))))
{
static foreach (ovl; __traits(getOverloads, genfun, fun))
{
void foobar(Parameters!ovl args) { // HERE
write("calling ");
foo(args); // HERE
}
}
}
}
}
void main()
{
foobar(1); // calling foo(1)
foobar(1, 2); // calling foo(1, 2)
}
Now I would like to change `foo` and `foobar` to calculated
symbols where marked. I would also like to use as little string
mixin as possible. I tried:
static foreach (fun; __traits(allMembers, genfun)) {
static if (fun == "foo") {
static if (is(typeof(__traits(getOverloads, genfun, fun))))
{
static foreach (ovl; __traits(getOverloads, genfun, fun))
{
void mixin(fun + "bar")(Parameters!ovl args) { // 1
write("calling ");
mixin(fun)(args); // 2
}
}
}
}
}
This gets me halfway there: #2 works but #1 does not.
This works:
static foreach (fun; __traits(allMembers, genfun)) {
static if (fun == "foo") {
static if (is(typeof(__traits(getOverloads, genfun, fun))))
{
static foreach (ovl; __traits(getOverloads, genfun, fun))
{
void internal(Parameters!ovl args) {
mixin(fun)(args);
}
mixin("alias %sbar = internal;".format(fun));
}
}
}
}
Does anyone see a potential problems with this? Or a better
solution? I would like to avoid the alias.
More information about the Digitalmars-d
mailing list