Make function alias

ag0aep6g anonymous at example.com
Mon Aug 20 13:35:07 UTC 2018


On 08/20/2018 03:14 PM, 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?

`writeln` is a template, so you can't do `&writeln`. You'd have to 
instantiate the template before you can get the function pointer: 
`&writeln!T`.

Even then you can't make an alias of that. `&writeln!T` is a function 
pointer, which is a value. But aliases work on types and symbols, not 
values.

If you manage to obtain aliases, you won't be able to use the ternary 
operator on them. Being an expression, `foo ? bar : baz` works on 
values. You can't use it with function aliases.

You have to commit to either function aliases or function pointers (values).

With aliases (no address-of operator, no ternary operator, `print` is 
not a template):

----
void log(bool newline = true)(string text)
{
    static if (newline) alias print = writeln;
    else alias print = writeln;
    print(text); /* Can't use UFCS with a local `print`, so 
`text.print()` doesn't work. */
}
----

With function pointers (have to instantiate `writeln`, `write`, and `print):

----
void log(bool newline = true)(string text)
{
     enum print(T ...) = newline ? &writeln!T : &write!T;

     print!string(text); /* No IFTI, because `print` isn't a function 
template. */
}
----


More information about the Digitalmars-d-learn mailing list