Delegate contravariance
Silvio Ricardo Cordeiro
silvioricardoc at gmail.com
Tue Jan 13 15:26:50 PST 2009
Is there any good reason why the following code doesn't work?
The function "foo" requires as its argument a delegate that
receives a B. This means that, because of the type soundness
of the D language, the delegate will only be called with instances
of B. Now, why can't it be "abc", then? The "abc" delegate just
happens to handle more than it is required...
class A { }
class B : A { }
void foo(void delegate(B b) dg) {}
auto abc = (A a) { }
auto qwe = (B b) { }
void main() {
foo(abc); // this line won't compile
foo(qwe);
}
BTW: Same thing happens for const(B). B "sort of" a derivative
of const(B), so it would make sense. Every possible argument that can
be passed to a delegate(B) can also be passed to a delegate(A) or
delegate(const(B)). Why the restriction, then? Am I missing something?
More information about the Digitalmars-d-learn
mailing list