Jeremie Pelletier escribió:
Andrei Alexandrescu wrote:
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

I can't think of an use for contravariant parameters, since a B is guaranteed to always be a A, I don't see the point of being able to declare fun(A).

The thing is you have this:

class C : A { }
C c;

void foo(B someB) {
  someB.fun(c);
}

If contravariant arguments are not supported then fun can only receive a B, not a C. If you want to pass any A you can't, but maybe B.foo relaxes the requirements on it's arguments. Of course you can pass B to it, which is already an A, but you can't pass a C which is another A. That's the use case.

I can't come up with a killer example for this, I know I used covariant return types in Java before but never contravariant argument types. But if it's possible to implement it, I'd go for it. It's the right thing to do. And academic people will thank you and be happy. :-)

Reply via email to