Cannot interpret struct at compile time

Lutger Blijdestijn lutger.blijdestijn at gmail.com
Sun May 8 11:19:37 PDT 2011


Robert Clipsham wrote:

> Hey all,
> 
> I was wondering if anyone could enlighten me as to why the following
> code does not compile (dmd2, latest release or the beta):
> ----
> struct Foo
> {
>      int a;
> }
> 
> string test()
> {
>          string str = "struct " ~ Foo.stringof ~ "_{";
>          foreach (j, f; Foo.tupleof)
>          {
>              enum fullFieldName = Foo.tupleof[j].stringof;
>              str ~= typeof(f).stringof ~ ' ' ~
> fullFieldName[Foo.stringof.length + 3 .. $];
>          }
>          return str ~ "}";
> }
> 
> void main()
> {
>      mixin(test());
> }
> ----
> If fails with the errors:
> test.d(9): Error: Cannot interpret Foo at compile time
> test.d(19): Error: cannot evaluate test() at compile time
> test.d(19): Error: argument to mixin must be a string, not (test())
> test.d(19): Error: cannot evaluate test() at compile time
> test.d(19): Error: argument to mixin must be a string, not (test())
> 
> Thanks,
> 

test also doesn't compile normally on my box, dmd errors on Foo.tupleof. Not 
sure if this is illegal or not. I think you want the allMembers trait or 
something similar. Something like this:

import std.traits;

string test(T)()
{
    string str = "struct " ~ T.stringof ~ "_{";
    alias FieldTypeTuple!T FieldTypes;
    foreach (i, fieldName; __traits(allMembers, T ) )
    {
        str ~= FieldTypes[i].stringof ~ " " ~ fieldName ~ ";";
    }
    return str ~ "}";
}

This works for your example but is a bit crude, I'm sorry for that, you'll 
have to modify it. ( allMembers also returns functions, including ctors 
while FieldTypeTuple doesn't. I also haven't read anything about the order 
in which FieldTypeTuple and allMembers return their elements )


More information about the Digitalmars-d-learn mailing list