Am 14.04.19 um 15:22 schrieb Adam D. Ruppe:
> [...]
> Though, I'd point out the mixin code doesn't have to be too ugly.
> Consider this:
> 
> void main()
> {
>     enum letters = ['A', 'B', 'C'];
> 
>     static foreach(ch; letters)
>     {
>         mixin(q{
>         void print}~ch~q{(int i) {
>             import std.stdio;
>             writeln(ch, " - ", i);
>         }
>     });
>     }
> 
>     printB(6);
> }
> 
> 
> Well, the name part is a big ugly, but the rest of it looks perfectly
> normal, and the compiler error message still give reasonable results.
At first I was very confused that this example even worked. Why does
`ch` get expanded in the call to writeln? It is part of the mixed in
string, so why does the string not simply include "writeln(ch, ...)" on
every iteration?

If you do not care about your code being compatible with -betterC, you
can use std.format to make the code even more readable (at least in my
opinion):

void main()
{
    import std.format : format;

    enum letters = ['A', 'B', 'C'];

    static foreach (ch; letters)
    {
        mixin(q{
            void print%s(int i) {
                import std.stdio;
                writeln(ch, " - ", i);
            }
        }.format(ch));
    }

    printB(6);
}

Reply via email to