contravariant argument types: wanna?

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Sep 22 19:38:15 PDT 2009


dsimcha wrote:
> == Quote from Andrei Alexandrescu (SeeWebsiteForEmail at erdani.org)'s article
>> Hello,
>> Today, overriding functions have covariant return types:
>> class A {
>>      A clone();
>> }
>> class B : A {
>>      B clone(); // fine, overrides A.clone
>> }
>> That is entirely principled and cool. Now the entire story is that
>> overriding function may have not only covariant return types, but also
>> contravariant argument types:
>> class A {
>>      A fun(B);
>> }
>> class B : A {
>>      B fun(A); // fine (in theory), overrides A.fun
>> }
>> Today D does not support contravariant arguments, but Walter told me
>> once he'd be quite willing to implement them. It is definitely the right
>> thing to do, but Walter would want to see a compelling example before
>> getting to work.
>> Is there interest in contravariant argument types? If so, do you know of
>> a killer example?
>> Thanks,
>> Andrei
> 
> If I understand covariance and contravariance right, this seems like a no-brainer
> and probably easy to implement if you already have a working familiarity with the
> DMD codebase.  What would there be to the implementation besides:
> 
> 1.  Making the compiler accept class hierarchies for which contravariant arguments
> are declared, and
> 2.  Inserting the necessary implicit upcasts.

There is no need to explicitly declare contravariance. Accepting 
contravariant parameters would simply extend the notion of overriding.

Implementation-wise, I suspect some trampolines would be needed. Do 
references to objects need adjustment when implicitly cast to references 
to interfaces?


Andrei



More information about the Digitalmars-d mailing list