Type inference and overloaded functions
Jonathan M Davis
jmdavisProg at gmx.com
Tue Dec 10 02:33:24 PST 2013
On Tuesday, December 10, 2013 11:19:45 Kenji Hara wrote:
> On Tuesday, 10 December 2013 at 09:28:27 UTC, Jonathan M Davis
>
> wrote:
> > On Tuesday, December 10, 2013 10:10:22 Namespace wrote:
> > auto staticLiteral(T, size_t n)(T[n] literal)
> > {
> >
> > return literal;
> >
> > }
> >
> > auto staticArray = staticLiteral([1, 2, 3, 4]);
>
> Why do you think this is possible? If an array literal should
> match _only_ dynamic array types, it would never work.
>
> Because compiler will try to match array literal to static array
> T[n]. The feature which I have described is working here.
It doesn't need to match only dynamic array types. The problem is when you
have an overload. e.g.
auto foo(T[] arr) {...}
auto foo(T[3] arr) {...}
foo([1, 2, 3]);
Silently selecting one of the two is bug-prone - especially if it's the static
one that gets selected, as in most cases, it would be the dynamic one which
matches. Having dynamic array literals implicitly convert to static arrays
when they're assigned to static arrays makes sense when there's no ambiguity.
And in general, something like staticLiteral should be unnecessary when
passing to a function, as the array literal would be treated as a dynamic
array or a static array depending on the function's parameters, but it could
be useful in cases where you want to be explicit about the type or when using
auto. And it may not be worth adding a function such as staticLiteral, but I
think that it's better than trying to add static array literals to the
language, particularly since we're trying to avoid adding features to the
language when they can be implemented in the standard library instead.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list