how to handle void arguments in generic programming ?
Philippe Sigaud
philippe.sigaud at gmail.com
Mon Nov 11 05:02:08 PST 2013
On Mon, Nov 11, 2013 at 4:52 AM, Timothee Cour <thelastmammoth at gmail.com> 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);
> }
Shouldn't that be:
import std.stdio;
void main(){
writelnIfNonVoid("ok"); // not writeln("ok")
writelnIfNonVoid();
}
void writelnIfNonVoid(T...)(T a){
static if(T.length)
writeln(a);
}
or, if you want to print an expression whenever its type is not
`void`, then test it with an `is()`:
import std.stdio;
import std.traits: isCallable, ReturnType;
import std.stdio;
void main(){
writelnIfNonVoid("ok");
writelnIfNonVoid({ writeln("ok");}); // { ... ;} is an anonymous function
}
void writelnIfNonVoid(T)(T a){
static if(isCallable!a && !is(ReturnType!(a) == void))
writeln(a()); // calling
else static if(!isCallable!a && !is(T == void))
writeln(a);
}
More information about the Digitalmars-d-learn
mailing list