Converting a POD struct to a class at compile-time ?

Klb via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 16 10:43:02 PDT 2014


Hello, I'd like to know if it's possible, using CTFE, mixin etc 
to convert a POD struct to a class at compile time.

I've reached the step where the string to mix-in is generated but 
I cant mix it:

-------------------------------------------------------------
import std.stdio;
import std.traits, std.typetuple;

static private template genClassFromStruct(S) if (is(S == struct) 
&(__traits(isPOD, S)))
{
     auto values = S.init.tupleof;
     auto types = typeid(typeof(values));
     auto names = __traits(allMembers, S);

     string genClassFromStruct()
     {
         string members;
         foreach(int i,t; RepresentationTypeTuple!S)
         {
             members ~= t.stringof ~ " " ~ names[i] ~ ";\r";
         }

         return
             "class c" ~ S.stringof ~
             "{" ~ ";\r"~
                 members ~
             "}";
     }
}

struct foo{ int a; float b;}
//mixin( genClassFromStruct!foo );

void main(string args[])
{
     foo Foo;
     //auto c = new cfoo;

     writeln( genClassFromStruct!foo );
}
-------------------------------------------------------------

The problem appends when un-commenting the mixin:

Error: static variable _names_field_0 cannot be read at compile 
time.


More information about the Digitalmars-d-learn mailing list