【问题标题】:How do you enumerate the names and types inside a struct or class at compile time in D?如何在 D 中编译时枚举结构或类中的名称和类型?
【发布时间】:2011-11-21 17:31:36
【问题描述】:

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

即执行以下操作:

struct Foo {
  int x;
  int y;
}

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

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

谢谢,

克里斯。

【问题讨论】:

  • 你真的需要在 compile 时进行这个枚举吗?因为从代码中我看到反射可以做你需要的。
  • @Iaroslav 你能给我举个例子说明如何在 D 中使用反射吗?
  • 是的,在编译时生成序列化函数会更(运行时)效率。
  • 抱歉,我看错了标签。我的坏

标签: reflection d compile-time


【解决方案1】:

像这样:

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/CyberShadow/ae/blob/master/utils/json.d#L107

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2022-07-14
    • 1970-01-01
    • 2013-04-07
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多