www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Getting all struct members and values with introspection avoiding

reply ParticlePeter <ParticlePeter gmx.de> writes:
I am logging arbitrary POD struct types with member names and 
data:

void printStructInfo( T )( T info ) {
   foreach( i, A; typeof( T.tupleof )) {
     enum attribName = T.tupleof[i].stringof;
     writefln( "%s : %s", attribName, mixin( "info." ~ attribName 
));
   }
}

Is there is some other way to evaluate info.attribName without 
using string mixins?

Cheers, PP
May 01 2016
parent reply "H. S. Teoh via Digitalmars-d-learn" <digitalmars-d-learn puremagic.com> writes:
On Sun, May 01, 2016 at 09:42:37AM +0000, ParticlePeter via Digitalmars-d-learn
wrote:
 I am logging arbitrary POD struct types with member names and data:
 
 void printStructInfo( T )( T info ) {
   foreach( i, A; typeof( T.tupleof )) {
     enum attribName = T.tupleof[i].stringof;
     writefln( "%s : %s", attribName, mixin( "info." ~ attribName ));
   }
 }
 
 Is there is some other way to evaluate info.attribName without using
 string mixins?
[...] Using typeof(T.tupleof) seems a bit circuitous. Here's how I'd do it: void printStructInfo( T )( T info ) { import std.stdio : writefln; foreach (memb; __traits(allMembers, T)) { writefln("%s: %s", memb, __traits(getMember, info, memb)); } } (For structs that have members other than data fields, you'll need a static if to filter out non-value members, but this should get you started.) T -- 2+2=4. 2*2=4. 2^2=4. Therefore, +, *, and ^ are the same operation.
May 01 2016
parent ParticlePeter <ParticlePeter gmx.de> writes:
On Sunday, 1 May 2016 at 10:13:47 UTC, H. S. Teoh wrote:
 On Sun, May 01, 2016 at 09:42:37AM +0000, ParticlePeter via 
 Digitalmars-d-learn wrote:
 I am logging arbitrary POD struct types with member names and 
 data:
 
 void printStructInfo( T )( T info ) {
   foreach( i, A; typeof( T.tupleof )) {
     enum attribName = T.tupleof[i].stringof;
     writefln( "%s : %s", attribName, mixin( "info." ~ 
 attribName ));
   }
 }
 
 Is there is some other way to evaluate info.attribName without 
 using string mixins?
[...] Using typeof(T.tupleof) seems a bit circuitous. Here's how I'd do it: void printStructInfo( T )( T info ) { import std.stdio : writefln; foreach (memb; __traits(allMembers, T)) { writefln("%s: %s", memb, __traits(getMember, info, memb)); } } (For structs that have members other than data fields, you'll need a static if to filter out non-value members, but this should get you started.) T
Thanks, I was searching for that! The given example is a simplification of my code. I do examine each member separately and treat accordingly, but eventually used the mixin version to get the build-in type values.
May 01 2016