On 02/10/2011 11:32 PM, Jesse Phillips wrote:
enum FileName : string {
> > file1 = "file1.ext",
> > file2 = "file2.ext"
> > }
> >
> > void main(string args[])
> > {
> > foreach(a; __traits(allMembers, FileName))
> > writeln(mixin("FileName." ~ a));
> > }
>
> Why the mixin? Is it (just) to have the output string computed at
compile-time?
The value of 'a' is the enum field name, not its value.
Oops! missed this point ;-) Thanks for the explanation, Jesse.
This gave me the opportunity to ask about a detail. The following cannot
compile because an argument to string mixin must be a (compile-time) constant:
unittest {
auto i = 1;
auto s = "i";
writeln(mixin("i")); // compiler happy up to here --> "1"
writeln(mixin(s)); // compiler unhappy --> "Error: argument to
mixin
// must be a string, not (s)"
}
But in your example the symbol a does not look like a constant, instead it the
loop variable. Do, how does it work? Or is it that the compiler is able to (1)
detect that the collection beeing traversed (__traits(allMembers, FileName)) is
a compile-time constant (2) unroll the loop so as to rewrite it first as:
foreach(a; ["file1", "file2"])
writeln(mixin("FileName." ~ a)); // ***
and then as:
writeln(FileName.file1);
writeln(FileName.file2);
But this doesn't work, neither:
auto xx=1, yy=2;
auto as = ["x","y"];
foreach(a; as)
writeln(mixin(a ~ a));
And in fact the line *** is laso not accepted.
So, finally, I understand your code, but not how the compiler processes it so
as to see it as a mixin with constant argument.
Denis
--
_________________
vita es estrany
spir.wikidot.com