digitalmars.D.learn - Pass template parameter into q{} string
- Andrey (4/24) Apr 01 2019 I don't understand how to pass template parameter "values1" into
- Marco de Wild (33/57) Apr 02 2019 A token string (q{}) is still a string literal[1] (but has
- Kagamin (12/12) Apr 08 2019 Maybe just use mixin template?
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;");orstatic foreach(value; qqq) mixin("bool " ~ value ~ " = false;");
Apr 01 2019
On Monday, 1 April 2019 at 17:32:29 UTC, Andrey wrote:Hello,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/strienum 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;");orstatic foreach(value; qqq) mixin("bool " ~ value ~ " = false;");
Apr 02 2019
Maybe just use mixin template? mixin template f(alias values) { static foreach(v;values) mixin("bool " ~ v ~ " = false;"); } int main() { enum string[] a=["a","b"]; mixin f!a; return 0; }
Apr 08 2019