Q: Populating a structure with RTTI

Myron Alexander someone at somewhere.com
Mon Jun 11 06:28:22 PDT 2007


Chris Nicholson-Sauls wrote:
> T populate (T) () {
>   T t;
>   t.tupleof[0] = 1;
>   t.tupleof[1] = 2;
>   t.tupleof[2] = "testing";
>   return t;
> }
> 
> Although its dangerous, but I'm sure you knew that already.
> 
> -- Chris Nicholson-Sauls

Thanks Chris.

I do have another problem that you may be able to help me with. Here is 
an example of how I would use the above:

> import std.stdio;
> import std.traits;
> 
> /* Example value object.
>  */
> struct ValueStruc {
>    char[] name;
>    int    age;
>    char[] addr1;
>    char[] addr2;
>    char[] addr3;
>    double balance;
> }
> 
> /* Typesafe database row object.
>  */
> struct Row(T ...) {
>    T              t;
>    bool[T.length] nullFlag;
> }
> 
> /* Simulate a typesafe fetch from the database.
>  */
> Row!(T) fetchOne(T ...) () {
>    Row!(T) r;
>    /+ Won't compile:
>    int i = 0;
>    r.t[i++] = "Myron";
>    r.t[i++] = 10;
>    r.t[i++] = "addr1";
>    r.t[i++] = "addr2";
>    r.t[i++] = "addr3";
>    r.t[i++] = 100001.10;
>    +/
>    r.t[0] = "Myron";
>    r.t[1] = 10;
>    r.t[2] = "addr1";
>    r.t[3] = "addr2";
>    r.t[4] = "addr3";
>    r.t[5] = 100001.10;
>    r.nullFlag[0] = false; 
>    r.nullFlag[1] = true; 
>    r.nullFlag[2] = false; 
>    return r;
> }
> 
> /* Fetch a typesafe record from the database and populate the struct.
>  */
> T fetchStruc(T) () {
>    static if (is (T == struct)) {
>       auto r = fetchOne!(FieldTypeTuple!(T))();
>       T t;
> 
>       /+ Won't compile:
>       for (int i = 0; i < T.tupleof.length; i++) {
>          t.tupleof[i] = r.t[i];
>       }
>       +/
> 
>       // My nasty hack to get it to work:
>       static if ( 0 < T.tupleof.length) t.tupleof[0] = r.t[0];
>       static if ( 1 < T.tupleof.length) t.tupleof[1] = r.t[1];
>       static if ( 2 < T.tupleof.length) t.tupleof[2] = r.t[2];
>       static if ( 3 < T.tupleof.length) t.tupleof[3] = r.t[3];
>       static if ( 4 < T.tupleof.length) t.tupleof[4] = r.t[4];
>       static if ( 5 < T.tupleof.length) t.tupleof[5] = r.t[5];
> 
>       return t;
>    } else {
>       static assert (0);
>    }
> }
> 
> void main () {
>    auto x = fetchStruc!(ValueStruc) ();
>    
>    writefln ("%s, %s, %s, %s, %s, %#.2f", x.name, x.age, x.addr1, x.addr2, x.addr3, x.balance);
> }

I would like to implement the "Won't compile" blocks but have no clue if 
it is even possible. I'm thinking either a mixin, or a compile time 
function or something to that effect would allow me to build the 
functions so I don't have to use a whole whackload of static ifs as I 
have done in the fetchStruc.

If I can get this right, would make my normal use-case much easier.

Thanks,

Myron.


More information about the Digitalmars-d-learn mailing list