static foreach / How to construct concatenated string?

Robert M. Münch robert.muench at saphirion.com
Sun Mar 8 17:24:14 UTC 2020


On 2020-03-07 16:41:47 +0000, MoonlightSentinel said:

> On Saturday, 7 March 2020 at 16:30:59 UTC, Robert M. Münch wrote:
>> Is this possible at all?
> 
> You can use an anonymous lambda to build the string in CTFE:
> 
> ------------------------------------------
> 
> struct S {
>      int a;
>      bool b;
> }
> 
> import std;
> 
> enum string sql = {
>      string s = "CREATE TABLE data(";
> 
>      static foreach(f; FieldNameTuple!S) {
>      	s ~= f ~ ",";
>      }
> 
> 	s ~= ");";
>      return s;
> } ();
> 
> pragma(msg, sql);
> 
> ------------------------------------------
> 
> This prints "CREATE TABLE data(a, b);"

Nice... is the enum a so called "manifest constant" for which the 
initializer is evaluated at compile time?

OT: The pragma seems to print the string twice... at least here on my side.

OT2: Looks like I have to read through the language spec again... and 
most likely over and over again, to have all these tricks at my 
finger-tips.

-- 
Robert M. Münch
http://www.saphirion.com
smarter | better | faster



More information about the Digitalmars-d-learn mailing list