Type inference and overloaded functions
Marco Leise
Marco.Leise at gmx.de
Tue Dec 10 00:51:05 PST 2013
Am Tue, 10 Dec 2013 08:29:02 +0100
schrieb "Kenji Hara" <k.hara.pg at gmail.com>:
> This is an intended behavior. An array literal has dynamic array
> type *by default*.
> But all of literals in D behave as polymorphic.
>
> char c = 'A'; // character literal has char type by default
> dchar d = 'A'; // but it may be implicitly typed as wchar/dchar
>
> string str = "hello";
> dstring dstr = "hello"; // string literal is implicitly typed as
> dstring
>
> int[] darr = [1,2,3];
> int[3] darr = [1,2,3]; // implicitly typed as int[3]
>
> So, an array literal [1,2,3] is implicitly convertible both to
> int[] and int[3].
> And, int[3] is more specialized than int[], so overload
> resolution will choose the first 'bar'.
>
> Kenji Hara
So this is how it works. I honestly wouldn't have come up with
this. Your example for char makes it clear why this implicit
type changing is in place. The OP still has a point though. If
they are so polymorphic and "try to specialize" as necessary,
then D's typeof(…) must always be in a Schrödinger cat-like
state and only decide on an actual result when it is clear from
static code analysis that every use of it's argument in the
program leads to the same concrete type.
Taking the following example as a failing case for this
analysis:
int[] arr1 = [1,2,3];
int[3] arr2 = [1,2,3];
writeln(typeof([1,2,3]).stringof);
It must lead to a compiler error informing the user that [1,2,3]
is simultaneously int[] and int[3].
--
Marco
More information about the Digitalmars-d-learn
mailing list