Aliasing multiple delegates to the same name - very strange behaviour

Meta jared771 at gmail.com
Sun Feb 25 05:01:40 UTC 2018


On Sunday, 25 February 2018 at 04:47:47 UTC, Nicholas Wilson 
wrote:
> On Sunday, 25 February 2018 at 04:06:43 UTC, Meta wrote:
>> I just filed this bug: 
>> https://issues.dlang.org/show_bug.cgi?id=18520
>>
>> Not only does the following code compile and link 
>> successfully, it prints 0 three times when ran:
>>
>> alias f = (int n) => 0;
>> alias f = (char c) => 'a';
>> alias f = (bool b) => false;
>>
>> void main()
>> {
>>     import std.stdio;
>>     writeln(f(int.init));  //Prints 0
>>     writeln(f(char.init)); //Prints 0
>>     writeln(f(bool.init)); //Prints 0
>> }
>> [...]
>> 4. Is there any different semantically or mechanically between 
>> my first and second examples?
>
> Type promotions to int maybe?
> Have you tried casting them?
>
>> void main()
>> {
>>     import std.stdio;
>>     writeln(f(cast(int)int.init));
>>     writeln(f(cast(char)char.init));
>>     writeln(f(cast(bool)bool.init));
>> }

Ah, I tried changing it to the following:

struct NoPromote {}

alias f = (int n) => 0;
alias f = (char c) => 'a';
alias f = (NoPromote np) => NoPromote();

void main()
{
     import std.stdio;
     writeln(f(int.init));       //Prints 0
     writeln(f(char.init));      //Prints 0
     writeln(f(NoPromote.init)); //Prints 0
}

And I get "Error: function literal __lambda5 (int n) is not 
callable using argument types (NoPromote)". It was already 
apparent from the fact that the program printed 0 each time, but 
this confirms that the first function literal is the only one 
that _really_ gets aliased to f. Actually, this is unnecessary, 
because if I just change the order and move the bool function up 
to be the first, I get "Error: function literal __lambda4 (bool 
b) is not callable using argument types (char)".

Did I mention how much I hate the fact that char and bool 
implicitly convert to int?




More information about the Digitalmars-d mailing list