On 06/20/2016 01:40 AM, Joerg Joergonson wrote:
public class Button(T : ButtonItem) : Widget { ... }
public class ButtonItem : Item
{
  void Do() { auto parent = (cast(Button!ButtonItem)this.Parent); }
  ...
}

All this works great! As long as Do is not being called from a derived
class

public class Slider(T : SliderItem) : Button!T { }
public class SliderItem : ButtonItem { }


The last two classes are truly empty. Now, when I use a Slider object,
things go to shit because the cast is invalid. this.Parent is of type
Slider!SliderItem.

It's the same setup as with the A and B things, right?

Parent is a Widget that holds a Slider!SliderItem. That's fine because Slider!SliderItem is derived from Button!SliderItem which is derived from Widget.

But Button!SliderItem does not derive from Button!ButtonItem. They both derive from Widget. So the cast fails.

But you think it should succeed, of course.

Is your position that Button!SliderItem should derive/inherit from Button!ButtonItem, enabling the cast, or do you suppose the cast should succeed because the fields are compatible?

I.e., should this work?

    class A {int x;}
    class B {int x;}
    A a;
    B b = cast(B) a;

SliderItem only sets the array type. So in Slider, I end up with a
SliderItem[] type then in ButtonItem's Do(which gets called since
SliderItem doesn't override), it tries to cast that down to a
ButtonItem. It should work. There is no reason it shouldn't logically.
There is no up casting.

Some terminology clarification: Casting from SliderItem to ButtonItem is upcasting. The other direction would be downcasting. Upcasting a single object is trivial and can be done implicitly. Downcasting must be done explicitly and may yield null.

You say that you cast from SliderItem to ButtonItem. But that's not what's done in your snippet above. You try to cast from Button!SliderItem to Button!ButtonItem. Completely different operation.

Reply via email to