why can't structs implement interfaces?

Bill Baxter wbaxter at gmail.com
Tue Nov 24 16:53:05 PST 2009


On Tue, Nov 24, 2009 at 4:38 PM, Daniel Keep
<daniel.keep.lists at gmail.com> wrote:
>
> (This is all off the top of my head.)
>

<nice explanation snipped -- thanks>

> Even then, there's a worse problem.  All interfaces can be cast to
> Object, and then upcast to any valid class.  This is done via the use of
> the first slot of the object's vtable, which contains the ClassInfo.

Well, except for those dreaded "IUnknown" COM interfaces.

> But if you allow structs as interfaces, you're suddenly in the position
> where you might not actually have an object at all.  If you tried to
> cast a struct to an Object, it might not actually fail; if you're lucky,
> you'll get a segfault.

Same as with IUnknown interfaces.

> The only solution there is to give structs a vtable.  At which point,
> congratulations, you've just re-invented classes.
>
> To allow structs to implement interfaces would require redesigning how
> interfaces are actually implemented.  You'd probably have to also
> redesign RTTI as well, object casting, etc.

But with good enough introspection, it should be possible to make
automatic class wrappers for structs that implement an interface by
forwarding to the struct.

That's probably mostly doable now, though probably with a frightening
assortment method signature string parsing and mixins.

--bb


More information about the Digitalmars-d-learn mailing list