Mixin Expressions, can't evalutate string variable
a at a.a
Thu Aug 5 13:13:02 PDT 2010
"Andrej Mitrovic" <andrej.mitrovich at gmail.com> wrote in message
news:i3f3a0$25fv$1 at digitalmars.com...
> Hmm.. ok. Adding immutable helps. I'm still a bit confused tho,
The key is that the argument to mixin() must be known at compile-time. When
the compiler reaches a mixin(...), it looks at the argument to mixin and
tries to evaluate it at compile-time, which may or may not be successful.
> because this will not compile:
> string input2 = "int y;";
"string input2" is a run-time variable.
When the compiler sees "mixin(input2)" it tries to evaluate the expression
"input2" at compile-time. When it does that, it notices that input2 is
mutable (ie, What if in between those two lines there was: "if(args.length >
3) input2 = someOtherString"?). Since the value can change at run-time, the
compiler doesn't know at compile-time what the value will be. So it can't
mix it in.
True, in this particular case it could figure it out, but not in the general
case, so it doesn't bother.
> But this will compile:
> immutable string input2 = "int y;";
The compiler sees "mixin(input2)". It tries to evaluate the expression
"input2" at compile-time. It sees that "input2" is immutable so it goes "Ah
ha! That's *never* going to change, so I know exactly what the value is
always going to be, so I can just plop it right in." Doing "enum input2"
would also work for the same reason.
> And this too will compile:
> string returnString(string input)
> return input;
> mixin(returnString("int y;"));
The compiler reaches the mixin and tries to evaluate "returnString("int
y;")" at compile-time. Thanks to CTFE, it's able to, so this works.
More information about the Digitalmars-d