Upcasting slice of class elements

Steven Schveighoffer schveiguy at yahoo.com
Fri Jan 5 23:33:06 UTC 2018


On 1/5/18 6:04 PM, H. S. Teoh wrote:
> 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.

Hm... I tried just this and it works:

X[] xs = [new Y];

I think for non-class types it may need more casting.

-Steve


More information about the Digitalmars-d-learn mailing list