July 27, 2007 Getting member type string | ||||
---|---|---|---|---|
| ||||
The problem is to write a generic function that would be able to take the name of a struct or class data member and return a string representing the type of that member, both at compile time and at run time. I came up with the following (hackish) solution (for dmd 2.003): // Had to add this to workaround the foreach on tuples bugs private template Members(T, size_t idx = 0) { static if (idx < T.tupleof.length) { const char[][] members = ([T.tupleof[idx].stringof] ~ Members!(T, idx + 1).members); const char[][] types = ([typeof(T.tupleof[idx]).stringof] ~ Members!(T, idx + 1).types); } else { const char[][] members = []; const char[][] types = []; } } string getMemberType(T)(string memberName) { foreach (i, s; Members!(T).members) { if (s.length > memberName.length && s[$ - memberName.length .. $] == memberName && s[$ - memberName.length - 1] == '.') return Members!(T).types[i]; } assert(false, "No member " ~ memberName ~ " for type " ~ T.stringof); } class A { char[][] a; } void main() { //writefln(a); static compileTime = getMemberType!(A)("a"); auto runTime = getMemberType!(A)("a"); writefln("Compile time: " ~ compileTime); writefln("Run time: " ~ runTime); } -------- Does anybody know a better way? Maybe using the new __traits? Thanks. |
Copyright © 1999-2021 by the D Language Foundation