D2.056
Function是一个包含函数名称和类型(分别为Name和Type)的结构。 Binds遍历Function结构列表,并返回mixin字符串。这个mixin为每个函数定义了一个新名称,并附加了“2”。
void f() { writeln("f"); }
void g() { writeln("g"); }
struct Function(string name, Prototype)
{
const string Name = name;
mixin("alias Prototype Type;");
}
string Binds(Functions...)()
{
string r;
foreach (F; Functions)
{
// error:
r ~= to!string(typeid(F.Type)) ~ " " ~ F.Name ~ "2 = &" ~ F.Name ~ ";";
}
return r;
}
int main()
{
mixin (Binds!(
Function!("f", void function()),
Function!("g", void function())
));
f();
//f2();
return 0;
}
编译时,
to!string(typeid(F.Type))
给出错误:Error: Cannot interpret & D13TypeInfo_PFZv6__initZ at compile time
called from here: to(& D13TypeInfo_PFZv6__initZ)
called from here: Binds()
首先,我不明白为什么需要显式转换为字符串(typeid是否不是字符串,如果不是,则typeid和typeof之间的区别是什么?)。
其次,我不知道如何写出显式函数类型以便可以在main中执行。我无法使用F.Type,因为它对于foreach是本地的。
最佳答案
您在这里遇到了几个问题,但主要的问题是typeid返回类型为TypeInfo(typeid expression)的对象。幸运的是,您可以只使用F.Type.stringof。还要注意,您不需要mixin将Prototype别名为Type:
void f() { writeln("f"); }
void g() { writeln("g"); }
struct Function(string name, Prototype)
{
const string Name = name;
alias Prototype Type;
}
string Binds(Functions...)()
{
string r;
foreach (F; Functions)
{
// error:
r ~= F.Type.stringof ~ " " ~ F.Name ~ "2 = &" ~ F.Name ~ ";";
}
return r;
}
import std.stdio,
std.conv;
int main()
{
mixin (Binds!(
Function!("f", void function()),
Function!("g", void function())
));
f();
f2();
return 0;
}
运行此打印:
f
f
我相信这就是您要寻找的。