Getting all struct members and values with introspection avoiding string mixins
user1234
user1234 at 12.de
Thu Oct 5 23:57:13 UTC 2023
On Thursday, 5 October 2023 at 22:24:06 UTC, mw wrote:
> On Thursday, 5 October 2023 at 21:41:38 UTC, cc wrote:
>>
>> If you have `T info`, T.tupleof[n] will always match up with
>> info.tupleof[n]. You can think of `info.tupleof[n]` as being
>> rewritten by the compiler in-place as
>> info.whateverFieldThatIs. You might try this version (note
>> the double {{ }} with static foreach):
>> ```d
>> void printStructInfo( T )( T info ) {
>> static foreach( i, A; info.tupleof ) {{
>> enum attribName = T.tupleof[i].stringof;
>> writefln( "%s : %s", attribName, info.tupleof[i] );
>> }}
>> }
>> ```
>>
>> Be advised that T.tupleof and __traits(allMembers, T) return
>> two different sets of things. allMembers will probably get
>> you a lot of stuff you don't want and will need to write
>> checks to avoid. Using .tupleof is a perfectly acceptable
>> practice.
>
>
> Thanks, this version does not include the alias.
Be aware however that `.tupleof[i]` create at compile time the
tuple, just to read a single element, when finally just one is
required.
More information about the Digitalmars-d-learn
mailing list