On Wednesday, 28 August 2013 at 05:13:51 UTC, H. S. Teoh wrote:
One trick that you may find helpful, is to use alias this to
simulate
struct inheritance:
struct Base {
int x;
}
struct Derived1 {
Base __base;
alias __base this;
int y;
}
struct Derived2 {
Base __base;
alias __base this;
int z;
}
void baseFunc(Base b) { ... }
void derivFunc1(Derived1 d) {
auto tmp = d.y;
auto tmp2 = d.x; // note: "base struct" member directly
accessible
}
void derivFunc2(Derived2 d) {
auto tmp = d.z;
auto tmp2 = d.x;
}
Derived1 d1;
Derived2 d2;
baseFunc(d1); // OK
baseFunc(d2); // OK
derivFunc1(d1); // OK
//derivFunc2(d1); // Error: Derived1 can't convert to Derived2
derivFunc2(d2); // OK
This won't help you if you need a single variable to store both
structs "derived" this way, though, 'cos you wouldn't know what
size the structs should be. You *could* get away with using
Base* (Base pointers) in a semi-polymorphic way as long as
you're sure the derived structs don't go out of scope before
the Base*, but it gets a bit tricky at that point, and you
start to need real classes instead.
Yes that could work, it's a bit how my templates work to get
around (some of) this problem. But it doesn't really help with
keeping it looking and feeling clean like it's suppose to. I
shouldn't have to fight the language to get something that's
effectively there already.
It's possible to have a pointer to the base manually added with
the alias this, I've done that for an experimental sorting struct
before, but even if THAT works, it will still work in the local
struct before it will work from the 'base' or where it inherited
from.
I've been thinking, perhaps i can get around it using a
DSL/mixins that will give me what i want while not touching the D
language, and hopefully the D language moves and gives me what i
want rather than doing mixin magic to glue it all together. But
then wrapping your mind around how it 'should work' and 'what it
actually does to get it working' will create very interesting
errors, plus it's all hidden so only by expanding and working
through a bunch of garbage would you figure it all out.
*sighs*
I'll post in the main D forum section regarding behavior of
inherited structs rather than my much larger post; Perhaps Walter
or Andrei might see what I want and have a better solution. Maybe
having inherited structs adds too much complexity for what a
struct should be.