lookup fields struct
    jerro 
    a at a.com
       
    Sun May 26 08:40:01 PDT 2013
    
    
  
On Sunday, 26 May 2013 at 14:19:13 UTC, mimi wrote:
> Hi!
>
> I am want to get list of fields types and offsets in struct by
> the template.
>
> I.e., lookup through this struct:
>
> struct S {
>
> int a;
> string b;
> someptr* c;
>
> };
>
> template Lookup!( S )(); returns something as:
>
> field #0, int, offset 0
> field #1, string, offset 8,
> field #2, someptr, offset 16
>
> How I can do this?
To get a TypeTuple containing this information you can do this:
template Lookup(S)
{
     template Field(int index_, Type_, int offset_)
     {
         enum index = index_;
         alias Type = Type_;
         enum offset = offset_;
     }
     template impl(int i)
     {
         static if(i == S.tupleof.length)
             alias impl =  TypeTuple!();
         else
             alias impl = TypeTuple!(
                 Field!(i, typeof(S.tupleof[i]), 
S.init.tupleof[i].offsetof),
                 impl!(i + 1));
     }
     alias Lookup = impl!0;
}
If you only want to format this information to a string it's even 
simpler:
string lookup(S)()
{
     auto r = "";
     S s;
     foreach(i, e; s.tupleof)
         r ~= xformat("field #%s, %s, offset %s\n",
             i, typeof(s.tupleof[i]).stringof, 
s.tupleof[i].offsetof);
     return r;
}
Then lookup!S will give you the string and you can use it at 
compile time or at run time.
    
    
More information about the Digitalmars-d-learn
mailing list