www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Iteration over structure fields and properties

reply Void-995 <void995 gmail.com> writes:
I really appreciate traits and what they are introducing into the 
process. I'm curious how I can iterate over all fields of the 
structure (s.tupleof pretty much works for that) and properties 
while ignoring methods and sub data types that defined inside of 
structure (they defined only as type, not the field but of course 
they got into __traits(allMembers, S)). The idea is to use 
foreach to easily print into console something like:

fieldNameA: fieldValueA
fieldNameB: fieldValueB
...
propertyNameA: propertyValueA
...
Sep 06
parent reply Jacob Carlborg <doob me.com> writes:
On 2017-09-06 09:36, Void-995 wrote:
 I really appreciate traits and what they are introducing into the 
 process. I'm curious how I can iterate over all fields of the structure 
 (s.tupleof pretty much works for that) and properties while ignoring 
 methods and sub data types that defined inside of structure (they 
 defined only as type, not the field but of course they got into 
 __traits(allMembers, S)). The idea is to use foreach to easily print 
 into console something like:
 
 fieldNameA: fieldValueA
 fieldNameB: fieldValueB
 ...
 propertyNameA: propertyValueA
 ...
You can use .tupleof and __traits(identifier) for this. -- /Jacob Carlborg
Sep 07
parent reply Void-995 <void995 gmail.com> writes:
On Thursday, 7 September 2017 at 07:09:29 UTC, Jacob Carlborg 
wrote:
 On 2017-09-06 09:36, Void-995 wrote:
 I really appreciate traits and what they are introducing into 
 the process. I'm curious how I can iterate over all fields of 
 the structure (s.tupleof pretty much works for that) and 
 properties while ignoring methods and sub data types that 
 defined inside of structure (they defined only as type, not 
 the field but of course they got into __traits(allMembers, 
 S)). The idea is to use foreach to easily print into console 
 something like:
 
 fieldNameA: fieldValueA
 fieldNameB: fieldValueB
 ...
 propertyNameA: propertyValueA
 ...
You can use .tupleof and __traits(identifier) for this.
Would it work with: property int propertyNameA() And how to get key names then? As I remember tupleof return tuple of fields only, at least what I got how it works.
Sep 07
parent Jacob Carlborg <doob me.com> writes:
On 2017-09-07 09:22, Void-995 wrote:

 Would it work with:
  property int propertyNameA()
No, for that you need the traits getFunctionAttributes [1] (I think all functions are returned) and getFunctionAttributes [2].
 And how to get key names then? As I remember tupleof return tuple of 
 fields only, at least what I got how it works.
You index the tuple and use the "identifier" trait. [1] https://dlang.org/spec/traits.html#getVirtualFunctions [2] https://dlang.org/spec/traits.html#getFunctionAttributes -- /Jacob Carlborg
Sep 08