On Wed, Aug 28, 2013 at 06:45:11AM +0200, Era Scarecrow wrote:
> On Wednesday, 28 August 2013 at 03:45:06 UTC, Andre Artus wrote:
> >Era,
> >
> >I haven't had time to go through your everything you wrote here
> >but are you looking to create some form of discriminated union
> >(AKA tagged union) using D structs?
> >
> >Do you have a specific problem you need to solve, or are you just
> >exploring the language?
> 
>  The tagged union struct does sorta match the basic idea. What i
> have is a structure that basically is just a single struct, however
> it's semi-polymorphic. (I guess that's obvious by the subject). What
> changes is only really behavior and rarely would it actually add
> more data, so inheriting and OOP fits it fairly well, however since
> structs can't inherit it becomes an issue. I can either inherit, or
> i can make the function(s) large and clunky and basically do it as
> C.
[...]

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.


T

-- 
Once bitten, twice cry...

Reply via email to