在D编译时,如何枚举结构或类中的名称和类型? [英] How do you enumerate the names and types inside a struct or class at compile time in D?

查看:93
本文介绍了在D编译时,如何枚举结构或类中的名称和类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you enumerate the names and types inside a struct or class at 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"

谢谢

克里斯。

推荐答案

像这样:

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

这篇关于在D编译时,如何枚举结构或类中的名称和类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆