问题
Should be rather simple but it's not.
Here's my code :
string cases()
{
string ret = "";
string[] methods;
methods = [__traits(derivedMembers,mixin("Math"))];
foreach (string s; methods) ret ~= "case \"" ~ s ~ "\": return Math."~s~"(params);";
methods = [__traits(derivedMembers,mixin("OtherClass"))];
foreach (string s; methods) ret ~= "case \"" ~ s ~ "\": return OtherClass."~s~"(params);";
return ret;
}
string execute(string what, string[] params)
{
switch (what)
{
mixin(cases());
default: break;
}
return "";
}
What I want to do :
const string[] arrayWithClassNames = ["Math","SomeClass"];
foreach (string s; arrayWithClassNames)
{
methods = ...
foreach ...
}
Rather simple huh? The thing is it complains that :
variable 's' cannot be read at compile time.
Any ideas?
回答1:
To create a compile-time loop, you need to iterate over a tuple. Try this:
alias classNames = TypeTuple!("Math","SomeClass");
foreach (string s; classNames)
{
...
}
来源:https://stackoverflow.com/questions/23078009/using-a-foreach-loop-variable-cannot-be-read