get a struct member pointer

Daniel Keep daniel.keep.lists at gmail.com
Sun Feb 15 21:47:31 PST 2009



Jeffry Nox wrote:
> struct A {
> 	uint id=0;
> 	char[] name;
> }
> 
> struct B {
> 	uint id=0;
> 	char[] title;
> }
> 
> void lookup(T)(T[] s, ***)
> {
>   char[] txt = s[0].***;
> }
> 
> as illustrated above, how can i get struct object property info as in *** so i can manipulate it inside the function lookup above? in function lookup, i didnt know what is the variable name for the char[], so *** pass in the 2nd parameter, question is how to pass that member info or pointer so that it works on different struct declarations?

At runtime?  You can't, really.  The only thing you could do is
something like this:

void lookup(T)(T[] s, size_t offset)
{
  char[] text = *cast(char[]*)(cast(void*)(&s[0]) + offset);
}

(Note: haven't tested that particular combination of casts; I don't
bother memorising this :P)

Or something to that effect.  If possible, it'd be safer to do this:

void lookup(T, char[] field)(T[] s)
{
  char[] text = mixin(`s[0].`~field);
}

  -- Daniel


More information about the Digitalmars-d-learn mailing list