Using a foreach loop — variable cannot be read

我怕爱的太早我们不能终老 提交于 2019-12-23 16:06:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!