Bug 15640 – type inference in variadic array params not working for classes

Status
RESOLVED
Resolution
WONTFIX
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2016-02-02T13:57:05Z
Last change time
2022-10-31T13:50:24Z
Assigned to
No Owner
Creator
Marc Schütz

Comments

Comment #0 by schuetzm — 2016-02-02T13:57:05Z
void test(T)(T[] args...) { import std.stdio; writeln(T.stringof); } class A { } class B : A { } class C : A { } void main() { test(1,2,3); // int test(4,5,6.9); // double test(new B(), new C()); } => template xx.test cannot deduce function from argument types !()(B, C) IMO `T` should be inferred as `A`. Note that the common type is already chosen for mixed numerical types; it's an arbitrary restriction for it not to work with classes.
Comment #1 by schuetzm — 2016-02-02T15:09:09Z
Note also that the following works, too: class A { } class B : A { } class C : A { } auto a = [new A(), new B()]; pragma(msg, typeof(a)); // A[]
Comment #2 by schuetzm — 2016-02-02T15:10:15Z
(In reply to Marc Schütz from comment #1) > Note also that the following works, too: > > class A { } > class B : A { } > class C : A { } > auto a = [new A(), new B()]; > pragma(msg, typeof(a)); // A[] ... should have been: auto a = [new B(), new C()]; But the result is just the same.
Comment #3 by razvan.nitu1305 — 2022-10-31T13:50:24Z
Generally, the compiler tries to find the common type between the arguments, however, the common type is chosen to be one of the types of the arguments. Having the compiler infer the common type in the general case will add more complexity to the compiler. However, for your use case you can just use template variadic parameters: ``` void test(A...)(A a) { import std.stdio; writeln(A.stringof); } class A { } class B : A { } class C : A { } void main() { test(1,2,3); // int test(4,5,6.9); // double test(new B(), new C()); } ``` This works. So this is not a bug in the compiler, it could be seen at most as an enhancement request, however, this does not buy us anything since we already have syntax that takes care of the case.