How do you enumerate the names and types inside a struct or class at compile time in D?

空扰寡人 提交于 2019-12-07 05:48:56

问题


How do you enumerate the names and types inside a struct or class at compile time?

i.e. to do the following:

struct Foo {
  int x;
  int y;
}

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

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

Thanks,

Chris.


回答1:


Like this:

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

Practical example: https://github.com/CyberShadow/ae/blob/master/utils/json.d#L107



来源:https://stackoverflow.com/questions/7496527/how-do-you-enumerate-the-names-and-types-inside-a-struct-or-class-at-compile-tim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!