function - D 编译时函数类型提取

标签 function prototype d compile-time

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

我相信这就是您要找的。

关于function - D 编译时函数类型提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8185484/

相关文章:

javascript - JavaScript 的 Object.prototype 行为是什么?

javascript - String(number) 是否在内部调用 number.toString?

c - 错误 : No previous prototype for function. 为什么会出现此错误?

d - 如何在 D 中以毫秒为单位获取当前 Unix 时间戳?

templates - 也许输入 D

python - TypeError: (function) takes exactly x arguments (给定x+1)

python - 如何在 PyCharm 的虚拟环境包中访问函数

c - 如何让 gcc 将包含函数调用的表达式识别为常量?

python - 如何从 python 函数的列表中选择一个项目?

sdl - 对 opEquals : Linker errors with Derelict3 Bindings to SDL2 的 undefined reference