Andrei Alexandrescu wrote:
Walter and I discussed last night about contravariance and all and could not find a compelling argument in favor of implementing contravariant arguments right now. The feature is nontrivial to implement, potentially surprising, and has a number of odd corner cases.

One feature that does get requested often in C++ and Java is the ability to choose which class/interface contains the method you want to override. Consider:

interface Lottery {  void draw();  }
interface Figure {  void draw();  }

class LotterySimulation : Lottery, Figure {
    override void draw();
}

Doesn't the override keyword trigger an error here? There are no method to override since you're implementing it for the first time.

Why would it matter to override both of them differently? You'd need extra work with the vtables to call either depending on the interface pointer its called from. And when called from LotterySimulation how would the compiler pick which one to call? To me it just seems backwards, I would just implement both algorithms in LotterySimulation.draw() since if you implement both interfaces you want that object to perform both draws, even if called from a Lottery interface you're still calling a LotterySimulation which is also aware of the Figure interface.

Right now draw() overrides both methods, but you'd want to override them separately. You could do so through an intermediate interface:

class Figure2 : Figure {  void draw2() { return draw(); }  }
class LotterySimulation : Lottery, Figure2 {
    override void draw();
    override void draw2();
}

There are a few problems with this, among which the fact that LotterySimulation now cannot inherit another class; the one class slot was occupied by Figure2.

So I was thinking of this:

class LotterySimulation : Lottery, Figure {
    override(Lottery) void draw();
    override(Figure) void draw();
}

This is easy to implement, scales well, and has good real world uses. What say you?


Andrei

From the news title I thought you meant override(T) where T is the covariant type for the contravariant override:

class A {
        void foo(B);
}
class B:A {
        override(B) void foo(A);
}

Which could just as well be used to generate covariant boilerplate prologs :)

As for the interface selection, I'm still asking, how would the compiler know what LotterySimulation.draw() calls into?

Jeremie

Reply via email to