Typed variadic template syntax?
Idan Arye
GenericNPC at gmail.com
Thu Jan 30 03:19:32 PST 2014
On Wednesday, 29 January 2014 at 22:16:57 UTC, Peter Alexander
wrote:
> On Wednesday, 29 January 2014 at 21:18:06 UTC, Etienne wrote:
>>>
>>> void exec(string command)(){
>>> foreach(str ; choice.splitter(".")){
>>> writeln(str);
>>> }
>>> }
>>
>> I'd like to take the opportunity to say how much I'd love to
>> be able to do a static foreach rather than use recursion.
>
> You can use TypeTuple for static foreach.
>
> void foo(int x)()
> {
> import std.stdio;
> writeln(x);
> }
>
> void main()
> {
> import std.typetuple;
> foreach (x; TypeTuple!(1, 2, 3))
> foo!x();
> }
>
> Notice that the loop variable x is used as a template parameter
> at compile time. The code expands to:
>
> foo!1();
> foo!2();
> foo!3();
Two problems:
1) You can't use `foreach` outside functions. That means that you
write:
struct Foo{
foreach(i;TypeTuple!(1,2,3)){
mixin("int num"~i.stringof~";");
}
}
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);
More information about the Digitalmars-d
mailing list