ushort calls byte overload

nkm1 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue May 30 22:49:08 PDT 2017


On Tuesday, 30 May 2017 at 21:16:26 UTC, Oleg B wrote:
> Hello. I have this code
>
> import std.stdio;
>
> void foo(byte a) { writeln(typeof(a).stringof); }
> void foo(short a) { writeln(typeof(a).stringof); }
> void foo(int a) { writeln(typeof(a).stringof); }
>
> void main()
> {
>     foo(0); // int, and byte if not define foo(int)
>     foo(ushort(0)); // byte (unexpected for me)
>     foo(cast(ushort)0); // byte (unexpected too)
>
>     foo(cast(short)0); // short
>     foo(short(0)); // short
>
>     ushort x = 0;
>     foo(x); // short
> }
>
> Is this a bug or I don't understand something?

Hm, interesting. I think what you're seeing here is an unexpected 
application of value range propagation: 
http://www.drdobbs.com/tools/value-range-propagation/229300211

None of these functions can be called with ushort without 
conversions. As the manual says:

The function with the best match is selected. The levels of 
matching are:
     no match
     match with implicit conversions
     match with conversion to const
     exact match

All of your functions require some implicit conversions (the 
ushort here can be converted to byte because of value range 
propagation). So the next rule is in effect - the functions are 
ordered and the "most specialized" is chozen. The byte function 
is the most specialized, so it is called.
Or something like that :)

> but if compiler find one-to-one correspondence it don't make 
> assumptions, like here?
Apparently then it just chooses the function that is "exact 
match".




More information about the Digitalmars-d-learn mailing list