implicit cast and overload priority
Paul Backus
snarwin at gmail.com
Fri Feb 14 15:58:26 UTC 2025
On Friday, 14 February 2025 at 04:28:25 UTC, Dom DiSc wrote:
> Why does this happen:
>
> ```d
> void foo(long x) { }
> void foo(ulong x) { }
>
> main()
> {
> foo(short(17)); // error: `foo` called with argument types
> `(short)` matches both: `foo(long x)` and: foo(ulong x)`
> }
> ```
>
> Why does a short match an unsigned type with same priority as a
> signed type?!?
> Clearly a longer type with matching signedness should always be
> a better match than a type that will discard the sign, no?
Here's the spec for overload resolution:
https://dlang.org/spec/function.html#function-overloading
In your example, both overloads have match level 2: "match with
implicit conversions". So the compiler attempts to figure out
which one is more specialized by checking whether the parameters
of one overload can be used to call the other overload.
* `long x` can be used to call `foo(ulong)`, so `foo(long)` is at
least as specialized as `foo(ulong)`.
* `ulong x` can be used to call `foo(long)`, so `foo(ulong)` is
at least as specialized as `foo(long)`.
Oops--it turns out both overloads are equally specialized! So you
get an ambiguity error.
More information about the Digitalmars-d-learn
mailing list