View mode: basic / threaded / horizontal-split · Log in · Help
September 05, 2007
Pseudo-multiple-inheritance for structs and disambiguation
I'm curious if this will work in future-D. If it does, it will be a huge 
improvement over C++, and almost give D the power of Eifel.

struct A
{
   int a;
   int c;
}

struct B
{
   int b;
   int c;  // Note that both A and B contain an element called c.
}



struct C
{
   A super_A;
   B super_B;

   alias super_A this;  // now we can refer to super_A.a and super_A.c as a 
and c respectively
   alias super_B this;  // now we can refer to super_B.b and super_B.c as b 
and c respectively
   //
   // Except - wait - we have introduced an ambiguity with c!
   // Let's resolve it...

   alias super_A.c c;  // now c refers unambiguously to super_A.c
   alias super_B.c d;  // and we can still refer to super_B.c as d
}

That said, I'd still prefer the normal inheritance syntax. I think the 
principle of least surprise demands it. So all that would then become...

struct C : A, B
{
   alias A.c c;
   alias B.c d;
}

Hmmm... That would cause the compiler some problems, because A and B are types, 
but I'm using them here as values. Perhaps instead it should be...

struct C : A, B
{
   alias super(A).c c;  // now c refers unambiguously to A.c
   alias super(B).c d;  // and we can still refer to B.c as d
}

where super(T) refers to the element of type T which C "extends". (Still no 
polymorphism. It's still all just syntactic sugar). And then, of course

C c;
A a = cast(A)c; // should be the same as A a = c.super(A);
B b = cast(B)c; // should be the same as B b = c.super(B);

Voila!
Top | Discussion index | About this forum | D home