On Monday, 1 April 2019 at 17:32:29 UTC, Andrey wrote:
Hello,
enum Key : string
{
          First = "qwerty",
          Last = "zaqy"
}

void main()
{
    enum decl(alias values1) = q{
        static foreach(value; values1)
            mixin("bool " ~ value ~ " = false;");
    };

    enum qqq = [Key.First, Key.Last];
    mixin(decl!qqq);
}

I don't understand how to pass template parameter "values1" into q{} string to get this output:
static foreach(value; [Key.First, Key.Last])
    mixin("bool " ~ value ~ " = false;");
or
static foreach(value; qqq)
    mixin("bool " ~ value ~ " = false;");

A token string (q{}) is still a string literal[1] (but has autocomplete on individual tokens in many IDEs). It does not substitute the text for the values. As such, you'd need to format the string like usual. The following code worked:

enum Key : string
{
          First = "qwerty",
          Last = "zaqy"
}

void main()
{
    import std.format;
    enum decl(alias values1) = q{
        static foreach(value; %s)
            mixin("bool " ~ value ~ " = false;");
    }.format(values1.stringof);

    enum qqq = [Key.First, Key.Last];
    mixin(decl!qqq);

    import std.stdio;
    writeln(qwerty);
}

Here we use the format function from the standard library. We have a format token (%s) in the original string, and replace it with `values1.stringof`. `.stringof` in this case means the original text used in the call site passed to argument values1 ("qqq"). (When we don't use `.stringof`, "First" and "Last" are not defined, as the compiler thinks qqq is an array of Keys instead of strings.) You could also use a string interpolation library (e.g. [2]) from Dub.

[1] https://dlang.org/spec/lex.html#token_strings
[2] http://code.dlang.org/packages/stri

Reply via email to