Delegate contravariance

Steven Schveighoffer schveiguy at yahoo.com
Tue Jan 13 15:39:31 PST 2009


"Silvio Ricardo Cordeiro" wrote
> 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?

I think it would be a worthy enhancement, but it currently isn't implemented 
or in the spec.  You should add a bugzilla enhancement if it isn't already 
there.

You should be able to cast to get around it, but of course, that is ugly and 
cumbersome:

foo(cast(void delegate(B b))abc);

-Steve 




More information about the Digitalmars-d-learn mailing list