why can't structs implement interfaces?

Bill Baxter wbaxter at gmail.com
Tue Nov 24 14:55:41 PST 2009


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


More information about the Digitalmars-d-learn mailing list