Make function alias

Paul Backus snarwin at gmail.com
Mon Aug 20 13:34:50 UTC 2018


On Monday, 20 August 2018 at 13:14:14 UTC, Andrey wrote:
> Hello,
> I want to make an alias to function "std.stdio.writeln" and 
> "std.stdio.write" and use it like:
>
>>static void log(bool newline = true)(string text)
>>{
>>    alias print(T...) = newline ? &writeln : &write;
>> 
>>    _file.print();
>>    text.print();
>>}
>
> Unfortunately, it doesn't work... Also tried with "enum print 
> ..." but also no success.
> How to do it correctly?

Since newline is a compile-time parameter, you can use `static 
if`:

static if (newline) {
     alias print = writeln;
} else {
     alias print = write;
}

Note that since this alias is local to the function, you cannot 
use it with UFCS, so you will have to write `print(text)` instead 
of `text.print()`.

Full example: https://run.dlang.io/is/SrBJdk


More information about the Digitalmars-d-learn mailing list