digitalmars.D.learn - Upcasting slice of class elements
- =?UTF-8?B?Tm9yZGzDtnc=?= (6/6) Jan 05 2018 Why isn't
- Adam D. Ruppe (8/14) Jan 05 2018 class X {}
- Steven Schveighoffer (13/21) Jan 05 2018 Hm... given that there is no other reference to xs, it should work. But
- H. S. Teoh (10/19) Jan 05 2018 Your original code snippet seems redundant. If you wanted an empty array
- Steven Schveighoffer (5/25) Jan 05 2018 Hm... I tried just this and it works:
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?
Jan 05 2018
On Friday, 5 January 2018 at 22:16:04 UTC, Nordlöw 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?class X {} class Y : X {} class Z : X {} Y[] ys = Y[].init; X[] xs = cast(X[])(ys); xs[0] = new Z; What happens to ys[0] there?
Jan 05 2018
On 1/5/18 5:16 PM, Nordlöw wrote:Why isn't    class X {}    class Y : X {}    X[] xs = cast(X[])(Y[].init); compilable in safe D?Hm... given that there is no other reference to xs, it should work. But obviously you have a different example in mind, as this makes no sense? This works: X[] xs = [new Y]; Which really isn't any different.What's unsafe about such a cast?In general: Y[] ys = ...; xs = cast(X[])ys; xs[0] = new X; ys[0].foo; // oops, ys[0] isn't really a Y any more. But in your specific case, I think the compiler should see that it's ok. -Steve
Jan 05 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.
Jan 05 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:Hm... I tried just this and it works: X[] xs = [new Y]; I think for non-class types it may need more casting. -SteveWhy 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.
Jan 05 2018