D编译时函数类型提取

时间:2011-11-18 16:18:21

标签: function prototype d compile-time

D2.056

Function是一个包含函数名称和类型的结构(分别是Name和Type)。绑定迭代一系列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的本地。

1 个答案:

答案 0 :(得分:2)

这里遇到了一些问题,但主要问题是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

我相信你正在寻找的东西。