www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Getting class member offsets at compile time

Is there any **good** way to iterate over the members fields of a class at
compile time via templates or CTFE?  With structs you can do:

void someCtfeFunction(Struct)() {
    foreach(tupleIndex, elem; Struct.init.tupleof) {
        // Do stuff.
    }
}

This doesn't work for classes because using .tupleof requires an instance, and
classes, being reference types that require heap allocations and stuff, can't
be initialized in CTFE or templates.  In my case, I'm trying to introspect the
offsets of the fields, so I don't actually need an instance.

The way I found was:

1.  Get all members using __traits(allMembers, SomeClass)  This returns an
array of strings.
2.  Iterate over these strings in a CTFE function and generate a bunch of code
for each one.  Build a string to mix in.  Put static if statements into this
string to bypass functions and other stuff that's not a field.
3.  Call the CTFE function.  Mix in the huge amount of code it generates.
Curse when builds for anything non-trivial require more memory than you have
address space.

Please tell me there's a better solution that I somehow didn't think of.
Oct 30 2009