Compile time data structure

Marek Janukowicz marek at janukowicz.net
Mon Sep 16 13:24:50 PDT 2013


Ali Çehreli wrote:
> Could you please provide complete code.

Sure. This is of course stripped down just for demonstration purposes:

struct Attr {
  string name;
}

mixin template Model() {

  static string[string] columns () {
    string[string] cols;
    alias type = typeof(this);
     // Basically - get all members with @Attr UDA and build AA out of those
    foreach( field; __traits(derivedMembers, type)) {
      static if( is(typeof(__traits(getAttributes, __traits(getMember, type,
field))) blah)) {
        foreach( uda; __traits(getAttributes, __traits(getMember, type,
field))) {
          static if (is (typeof(uda) == Attr)) {
            static if (uda.name == "") cols[field] = field;
            else cols[field] = uda.name;
          }
        }
      }
    }
    return cols;
  }

  alias typeof(this) Me;

  static Me initialize () {
    Me me = new Me();
    foreach( attr, col; columns() ) {
      __traits(getMember, me, attr) = typeof(__traits(getMember, me, 
attr)).init;
    }
    return me;
  }

}

class ExampleModel {

  @Attr() int id;
  @Attr( "field_id" ) int fieldId;

  mixin Model;
}


void main () {
  ExampleModel ex = ExampleModel.initialize();
}

-- 
Marek Janukowicz


More information about the Digitalmars-d-learn mailing list