Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 581
fadedbee Avatar asked Sep 21 '11 08:09

fadedbee


1 Answers

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

like image 107
Vladimir Panteleev Avatar answered Sep 28 '22 11:09

Vladimir Panteleev