Structs implementing interfaces in D1
Steven Schveighoffer
schveiguy at yahoo.com
Tue Feb 10 06:42:11 PST 2009
"Tom S" wrote
> /**
> The concept is pretty simple. The mixin creates a vtable which points to a
> set of generated functions of the form { adjust the 'this' ptr; jump to
> the real function; }. Finally, the "InterfaceName asInterfaceName()"
> functions generated inside the struct return pointers to the corresponding
> vtables.
>
> Now this would be so much nicer if there was a way to iterate the
> functions of an interface at compile time in D1... Can we have D1 plus
> __traits? Pleaaaase? Pretty please with a cherry on top?
>
> Thanks to downs, Hxal and Jarrett!
> */
very, very cool.
However, I don't like the vtable-per-instance penalty.
Since structs are generally stack variables, why not make the interface a
separate stack variable? Most of the time, you are interested in passing a
struct to a function via an interface so the function can use the interface
but not save a reference to it.
i.e.:
interface I
{
int x();
}
int foo(I i)
{
return i.x;
}
struct S
{
int x() { return 1;}
}
struct Impl(Intf, Struct)
{
Struct *thisptr;
// template-mixin-fu goes here
Intf opCast() {...}
}
void bar()
{
S s;
auto si = Impl!(I, S)(s);
foo(cast(I)si);
}
With this, you could probably build a composite struct which has the vtable
and instance included inside one entity, so you can get back to the original
idea if you want to say put things in an array. There could even be a
template for that too.
This is sort of how I envisioned compiler-supported struct interfaces
working anyways (generate a stack "interface" every time you use the struct
as its implemented interface).
-Steve
More information about the Digitalmars-d
mailing list