www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Metaprogramming get type and field at compile time

reply bioinfornatics <bioinfornatics fedoraproject.org> writes:
Dear,

I use FieldTypeTuple and FieldNameTuple to get type and 
correponding field name but I fail to loop over these tuple.

As example:

struct Person{
     private string name;
     private ushort age;
     private bool   isMale;

     this(string name, ushort age, bool   isMale){
         this.name    = name;
         this.age     = age;
         this.isMale  = isMale;
     }
}

I would like to print with pragma msg:
  string name
  ushort age
  bool   isMale

for this I tried:

template getDeclarationFields( FieldTypeName...){
     enum typeIndex  = 0;
     enum nameIndex  = FieldTypeName.length / 2;
     enum  res       = FieldTypeName[typeIndex] ~ ' ' ~ 
FieldTypeName[nameIndex] ~';';
     static if( FieldTypeName.length == 1)
         enum getDeclarationFields = res;
     else
         enum getDeclarationFields = res ~ getDeclarationFields!( 
FieldTypeName[typeIndex+1..nameIndex] ~ 
FieldTypeName[nameIndex+1..$] );
}

but that don't build

I though that orange lib should do this somewhere but the lib usi 
his self trait method

thanks for your help
Oct 27 2015
parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 10/27/2015 03:34 PM, bioinfornatics wrote:

 I use FieldTypeTuple and FieldNameTuple to get type and correponding
 field name but I fail to loop over these tuple.
You can use the .tupleof property and a compile-time foreach: http://dlang.org/class.html (Search for .tuplof on that page) http://ddili.org/ders/d.en/tuples.html#ix_tuples..tupleof http://ddili.org/ders/d.en/tuples.html#ix_tuples.compile-time%20foreach Ali
Oct 27 2015
parent bioinfornatics <bioinfornatics fedoraproject.org> writes:
On Tuesday, 27 October 2015 at 22:53:35 UTC, Ali Çehreli wrote:
 On 10/27/2015 03:34 PM, bioinfornatics wrote:

 I use FieldTypeTuple and FieldNameTuple to get type and
correponding
 field name but I fail to loop over these tuple.
You can use the .tupleof property and a compile-time foreach: http://dlang.org/class.html (Search for .tuplof on that page) http://ddili.org/ders/d.en/tuples.html#ix_tuples..tupleof http://ddili.org/ders/d.en/tuples.html#ix_tuples.compile-time%20foreach Ali
wow Nice without traits thanks Ali for your amazing work best regards
Oct 27 2015