Using foreach loop - variable cannot be read

It should be pretty simple, but it is not.

Here is 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, just huh? The fact is that he complains that:

variable 's' cannot be read at compile time. 

Any ideas?

+3
source share
1 answer

To create a compilation loop, you need to iterate over the tuple. Try the following:

alias classNames = TypeTuple!("Math","SomeClass");
foreach (string s; classNames)
{
    ...
}
+5
source

Source: https://habr.com/ru/post/1536543/


All Articles