How to do "inheritance" in D structs

TheFlyingFiddle via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 11 19:18:47 PDT 2016


On Wednesday, 12 October 2016 at 01:22:04 UTC, lobo wrote:
> Hi,
>
> I'm coming from C++ and wondered if the pattern below has an 
> equivalent in D using structs. I could just use classes and 
> leave it up to the caller to use scoped! as well but I'm not 
> sure how that will play out when others start using my lib.
>
> Thanks,
> lobo
>
>
> module A;
>
> class Base1 {
>     int ival = 42;
> }
> class Base2 {
>     int ival = 84;
> }
>
> module B;
>
> class S(ABase) : ABase {
>     string sval = "hello";
> }
>
> module C;
>
> import A;
> import B;
>
> void main() {
>     auto s= scoped!(S!Base1); // scoped!(S!Base2)
> }

You could use "alias this" to simulate that type of inheritence.

module A;
struct Base1
{
     int ival = 42;
}

module B;

struct Base2
{
     int ival = 84;
}

module C;
import A, B;

struct S(Base) if(is(Base == struct))
{
     Base base;
     alias base this;
     string sval = "Hello ";
}

void foo(ref ABase base)
{
     base.ival = 32;
}

void main()
{
     S!Base1 a;
     S!Base2 b;
     writeln(a.sval, a.ival);
     writeln(b.sval, b.ival);
     foo(a);
     writeln(a.sval, a.ival);
}


More information about the Digitalmars-d-learn mailing list