how to handle void arguments in generic programming ?

Timon Gehr timon.gehr at gmx.ch
Mon Nov 11 05:06:14 PST 2013


On 11/11/2013 04:52 AM, Timothee Cour wrote:
> The code snippet below doesn't work. Is there a way to make it work?
>
> import std.stdio;
> void main(){
>    writelnIfNonVoid(writeln("ok"));
> }
> void writelnIfNonVoid(T...)(T a){
>    static if(T.length)
>      writeln(a);
> }


import std.stdio;
void main(){
     writelnIfNonVoid(writeln("ok"));
}
void writelnIfNonVoid(T...)(lazy T a){
     static if(T.length){
         static if(is(T[0]==void)) a[0];
         else write(a[0]);
         static if(T.length==1) writeln();
         else writelnIfNonVoid(a[1..$]);
     }
}

Or, if you care about evaluation order and locking stdout:

import std.stdio;

void main(){
     writelnIfNonVoid(writeln("ok"));
}
void writelnIfNonVoid(T...)(lazy T a){
     import std.range, std.algorithm, std.conv;
     mixin({
         string[] 
indices=iota(a.length).map!(i=>"a["~to!string(i)~"]").array~"cast(void)0";
         string r;
         foreach(i,t;T){
             if(is(t==void))
                 indices[i+1]="("~indices[i]~","~indices[i+1]~")";
             else r~=indices[i]~",";
         }
         if(r.length) r="writeln("~r~");";
         return r~indices[$-1]~";";
     }());
}




More information about the Digitalmars-d-learn mailing list