contravariant argument types: wanna?

Steven Schveighoffer schveiguy at yahoo.com
Tue Sep 22 19:22:43 PDT 2009


On Tue, 22 Sep 2009 21:15:54 -0400, Steven Schveighoffer  
<schveiguy at yahoo.com> wrote:


> BTW, I don't see a huge benefit from your example.  If B inherits from  
> A, then B knows about all the types A knows about (imagining an example  
> where the parameters were some other class hierarchy, like C and D), so  
> does it make a lot of sense to limit the arguments to B.fun to a base  
> class of something B must already know about?  I mean, it's not like B  
> doesn't know about the derived type, how hard would it be to just use  
> the derived type?  Maybe I'm missing something...
>

OK, here is an abstract example, maybe someone can put some real-world  
use-case to it.

I have a base class A which I want to override, but I also want to  
implement interface I (assuming I didn't write either of them).  They are  
defined as follows:

// parameter classes
class X {}
class Y: X {}

class A
{
    void foo(Y y) {}
}

interface I
{
    void foo(X x);
}

With contravariance, I could do:

class B : A, I
{
    void foo(X x) {...}
}

Without contravariance, I don't see how it could be done...

-Steve



More information about the Digitalmars-d mailing list