Array type inference annoyance
H. S. Teoh
hsteoh at quickfur.ath.cx
Wed Nov 20 21:46:26 PST 2013
class Base { ... }
class Derived1 : Base { ... }
class Derived2 : Base { ... }
void func(Base[] objs) { ... }
func([
new Derived1(),
new Derived2() // OK
]);
Derived2 d2ptr;
func([
new Derived1(),
d2ptr = new Derived2() // NG: compile error (WAT?)
]);
// Workaround:
func([
cast(Base) new Derived1(), // ugh
d2ptr = new Derived2() // OK
]);
According to TDPL (§2.2.6, p.40), the type of array literals are
inferred by applying the ?: operator to elements pairwise. But the
second call to func() above fails in spite of the fact that this code
passes:
static assert(is(typeof(true ? new Derived1() : (d2ptr =
newDerived2())) == Base));
The necessity of the cast as in the workaround is really ugly, and is a
fly in my otherwise pleasant D soup currently. :-(
T
--
Talk is cheap. Whining is actually free. -- Lars Wirzenius
More information about the Digitalmars-d
mailing list