Mixin Expressions, can't evalutate string variable

Tomek Sowiński just at ask.me
Thu Aug 5 12:21:56 PDT 2010


Tomek Sowiński napisał:

> Andrej Mitrovic napisał:
> 
>> I think this should work:
>> 
>> string s = "int x;";
>> mixin(s);
>> 
>> void main()
>> {
>>     
>> }
>> 
>> But I get:
>> testtest.d(11): Error: argument to mixin must be a string, not (s)
>> 
>> I get a similar error with the template example from the docs:
>> 
>> template GenStruct(string Name, string M1)
>> {
>>     string GenStruct = "struct " ~ Name ~ "{ int " ~ M1 ~ "; }";
>> }
>> 
>> mixin(GenStruct!("Foo", "bar"));
>> 
>> void main() { }
>> 
>> testtest.d(27): Error: argument to mixin must be a string, not
>> (GenStruct)
>> 
>> 
>> This is really weird, I swear it worked for me a couple of days ago. :s
>> Maybe I accidentally modified a library file, so I'll have a look.
>> Meanwhile can someone succesfully compile these?
> 
> template GenStruct(string Name, string M1)
> {
>     immutable string GenStruct = "struct " ~ Name ~ "{ int " ~ M1 ~ "; }";
> }
> 
> It must be immutable to be seen as a template expression. Otherwise it's
> one mutable string declaration that happens to be named same as the
> enclosing template.

To avoid the WTF you may find CTFE useful (and easier on the eye):

string GenStruct(string Name, string M1) {
    return "struct " ~ Name ~ "{ int " ~ M1 ~ "; }";
}
mixin(GenStruct("Foo", "bar"));


Tomek


More information about the Digitalmars-d mailing list