Array of interface only with cast()?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 22 08:34:01 PDT 2014


On Tue, 22 Apr 2014 11:19:57 -0400, Andre <andre at s-e-a-p.de> wrote:

> Hi,
>
> I just stumbled about this issue with array of interface. I want
> to pass several objects (C and D) which shares the same interface A.
> It seems somehow cumbersome that it only works if there is a cast on
> the first element of the array.
>
> interface A{}
>
> class B: A{}
>
> class C: B{};
> class D: B{};
>
> void main()
> {
> 	//A[] arr = [new C(), new D()]; // Does not work
> 	A[] arr = [cast(A) new C(), new D()]; // Does work
> }
>
> Is the cast really needed?

At this point, yes. This is because the expression [new C(), new D()] does  
not take into account what you are assigning to (IMO it should).

The compiler will use the most derived type possible that all the elements  
implicitly cast to. In this case, it will be a B[].

-Steve


More information about the Digitalmars-d-learn mailing list