Upcasting slice of class elements

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Jan 5 23:04:06 UTC 2018


On Fri, Jan 05, 2018 at 10:16:04PM +0000, Nordlöw via Digitalmars-d-learn wrote:
> Why isn't
> 
>     class X {}
>     class Y : X {}
>     X[] xs = cast(X[])(Y[].init);
> 
> compilable in safe D?
> 
> What's unsafe about such a cast?

Your original code snippet seems redundant. If you wanted an empty array
of X's, there's no need to cast it from an array of Y's.

Perhaps you had something like this in mind instead?:

	X[] xs = [ cast(X) new Y(...), new Y(...), ... ];

The cast is only needed for the first element; common type inference
takes care of the rest of the array.


T

-- 
Give a man a fish, and he eats once. Teach a man to fish, and he will sit forever.


More information about the Digitalmars-d-learn mailing list