5

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

即执行以下操作:

struct Foo {
  int x;
  int y;
}

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

auto f = Foo(1,2);
serialise(f); -> "x:1, y:2"

谢谢,

克里斯。

4

1 回答 1

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);
}

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

于 2011-09-21T08:41:05.030 回答