应该相当简单,但事实并非如此。
这是我的代码:
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 "";
}
我想做什么:
const string[] arrayWithClassNames = ["Math","SomeClass"];
foreach (string s; arrayWithClassNames)
{
methods = ...
foreach ...
}
相当简单吧?事情就是抱怨:
variable 's' cannot be read at compile time.
有什么想法吗?
答案 0 :(得分:5)
要创建编译时循环,需要迭代元组。试试这个:
alias classNames = TypeTuple!("Math","SomeClass");
foreach (string s; classNames)
{
...
}