如何在D中编译时枚举结构或类中的名称和类型?

fad*_*bee 5 reflection d compile-time

如何在编译时枚举结构或类中的名称和类型?

即执行以下操作:

struct Foo {
  int x;
  int y;
}

string serialise!(A)(A a) {
  ...magic...
}

auto f = Foo(1,2);
serialise(f); -> "x:1, y:2"
Run Code Online (Sandbox Code Playgroud)

谢谢,

克里斯.

Vla*_*eev 8

像这样:

foreach (index, field; myStruct.tupleof)
{
    // field.stringof is "field", slice is to cut off "myStruct."
    pragma(msg, "Name: " ~ myStruct.tupleof[index].stringof[9..$]);
    pragma(msg, "Type: " ~ typeof(field).stringof);
}
Run Code Online (Sandbox Code Playgroud)

实际例子:https://github.com/Cyber​​Shadow/ae/blob/master/utils/json.d#L107