array of elements of various sybtypes

Jesse Phillips jessekphillips+D at gmail.com
Wed Jan 26 10:29:04 PST 2011


spir Wrote:

> Hello,
> 
> This fails:
> 
> class T0 {}
> class T1 : T0 {}
> class T2 : T0 {}
> 
> unittest {
>      auto t1 = new T1();
>      auto t2 = new T2();
>      T0[] ts = [t1, t2];
> }
> 
> Error: cannot implicitly convert expression (t1) of type __trials__.T0 to 
> __trials__.T2
> Error: cannot implicitly convert expression ([(__error),t2]) of type T2[] to T0[]

D takes the type of the last element. I guess it has been decided to take the common type but hasn't been implemented. Anyway your two reasonable options are:

auto ts = to!(T0[])([...]);

auto ts = [new T1(), to!(T0)(new T2())]

I recommend using std.conv.to instead of a cast because it is safer. Though cast is a no-op and isn't any less safe in this case.


More information about the Digitalmars-d-learn mailing list