Implicit Interface Deduction

Chris Wright via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Dec 13 17:45:52 PST 2015


On Sun, 13 Dec 2015 23:09:47 +0100, Faux Amis wrote:

> interface IA {}
> interface IB {}
> interface IC {}
> interface IAB : IA, IB {} interface IBC : IB, IC {}
> 
> class C : IA, IB, IC {}
> // Defining C as : IAB, IBC // is not really scalable ;)
> 
> void main()
> {
>   IAB c = new C(); // This doesn't work.
> }
> // Any suggestions?

If you really can't modify the declaration to suit, there are two options.

The first is to use casts. If a function would require something that's 
both IA and IB, it takes an IA and casts to IB. It can use contracts to 
ensure that things are of the right type. Ugly, but it works.

The second is to use templates to generate the interface you need and 
appropriate wrapper classes. Then you need to manually wrap variables in 
those generated wrapper classes wherever you need to pass them. You'll 
end up with an API like:

alias IABC = Union!(IA, IB, IC);
void foo(IABC.Interface iabc) {}
auto c = new C;
foo(IABC.wrap(c));

If you really want to go this way, std.typecons might help. Or I hacked 
up something horrific here: http://dpaste.dzfl.pl/0464f723580f


More information about the Digitalmars-d-learn mailing list