www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Pass template parameter into q{} string

reply Andrey <saasecondbox yandex.ru> writes:
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;");
Apr 01
next sibling parent Marco de Wild <mdwild sogyo.nl> writes:
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
Apr 02
prev sibling parent Kagamin <spam here.lot> writes:
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