Typed variadic template syntax?

Ilya Yaroshenko ilyayaroshenko at gmail.com
Thu Jan 30 09:13:19 PST 2014


On Thursday, 30 January 2014 at 15:28:34 UTC, Timon Gehr wrote:
> On 01/30/2014 03:08 PM, Ilya Yaroshenko wrote:
>>>
>>> 2) `foreach` creates it's own scope. This won't work:
>>>    foreach(i; TypeTuple!(1,2,3)){
>>>        mixin("int num"~i.stringof~";");
>>>    }
>>>    num1=1;
>>>    num2=2;
>>>    num3=3;
>>>    writeln(num1,num2,num3);
>>
>> ...
>> 2) no. This should work for compile time foreach and 
>> TypeTuples. There
>> are many examples in source code of Phobos.
>
> The following code fails to compile:
>
> import std.typetuple, std.stdio;
> void main(){
>     foreach(i; TypeTuple!(1,2,3)){
>         mixin("int num"~i.stringof~";");
>     }
>     num1=1;
>     num2=2;
>     num3=3;
>     writeln(num1,num2,num3);
> }

I am wrong, foreach always has own scope

     foreach(S; TypeTuple!(string, wstring, dstring))
     {
         import std.conv : to;
         S a = " a     bcd   ef gh ";
         assert(equal(splitter(a), [to!S("a"), to!S("bcd"), 
to!S("ef"), to!S("gh")]));
         a = "";
         assert(splitter(a).empty);
     }


You can use mixin and format instead:

import std.typetuple, std.stdio;
void main(){
     mixin(format("%(int num%s; %);", [1,2,3])); //<----
     num1=1;
     num2=2;
     num3=3;
     writeln(num1,num2,num3);
}



More information about the Digitalmars-d mailing list