Compile time data structure

Marek Janukowicz marek at janukowicz.net
Sun Sep 15 16:20:57 PDT 2013


I need to gather some data in compile time basing on UDA.

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;
  }
}

class ExampleModel {

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

  mixin Model;
}

This works and the result of columns() method is as expected. However, if I 
try to use it in another compile time fuction, eg:

    foreach( attr, col; columns ) {
      __traits(getMember, obj, attr) = 1;
    }

it fails saying "attr" cannot be read at compile time. 

I suspect I can't just build AA during compile time, but is there any other 
way for columns() method to return a structure that could be further 
evaluated at compile time?

-- 
Marek Janukowicz


More information about the Digitalmars-d-learn mailing list