www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - lookup fields struct

reply "mimi" <4.deniz.z.z gmail.com> writes:
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:





How I can do this?
May 26 2013
next sibling parent "evilrat" <evilrat666 gmail.com> writes:
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:





 How I can do this?
std.traits and built-in traits should do what u asking. http://dlang.org/phobos/std_traits.html http://dlang.org/traits.html
May 26 2013
prev sibling parent reply "jerro" <a a.com> writes:
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:





 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) 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.
May 26 2013
parent reply "mimi" <4.deniz.z.z gmail.com> writes:
Wow! thanks!
May 26 2013
parent "Diggory" <diggsey googlemail.com> writes:
On Sunday, 26 May 2013 at 23:37:01 UTC, mimi wrote:
 Wow! thanks!
"offsetof" will automatically distribute over the arguments so to get the offsets of a tuple you can just do: auto tmp = TP.offsetof; And "tmp" will be a tuple of the offsets.
May 26 2013