why can't structs implement interfaces?

Lutger lutger.blijdestijn at gmail.com
Tue Nov 24 15:09:11 PST 2009


Bill Baxter wrote:

> On Tue, Nov 24, 2009 at 2:49 PM, Saaa <empty at needmail.com> wrote:
>> bearophile wrote:
>>> Moritz Warning:
>>>
>>>> If you only what a contract that certain functions are implemented,
>>>> then it just need to be implemented in the compiler frontend.
>>>
>>> In the meantime this can be done with a template mixin, where the
>>> template statically asserts the presence of the functions/fields you
>>> want.
>>>
>>> Bye,
>>> bearophile
>>
>> I wanted to do something like this:
>>
>> class C : I {};
>> struct S : I {};
>> S s;
>> I[] i =[new C(), s ];
> 
> Yeh, that's never going to work because that's acting as a dynamic
> polymorphic interaface.  Referring polymorphically to a struct like
> that pretty much makes it not a struct anymore, and requires having
> the hidden pointer to a vtable that was mentioned.  That's what
> classes are for.
> 
> In D2 you can use "alias this" inside a class to forward things to the
> struct, though. Something like this:
> 
> class ClassWrapper(S) : I {
>    S _impl;
>    alias _impl this;
> }
> 
> But I somehow doubt DMD will consider methods handled by S as being an
> implementation of the interface.
> So you'll need explicit forwarding.
> 
> --bb

I can confirm that it is not possible with alias this. 

Somewhat related, template mixins can add virtual methods:

template T() { /*implementation of I*/ }
class C : I  { mixin T!(); } // adds methods in T!() as virtual methods







More information about the Digitalmars-d-learn mailing list