How to do "inheritance" in D structs

Jacob Carlborg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 11 23:32:57 PDT 2016


On 2016-10-12 03:22, 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)
> }

Depending on what you need, any alternative to structs and "alias this" 
would be to use structs with template mixins [1]:

mixin template Base1()
{
     int ival = 42;
}

struct S(ABase)
{
     mixin ABase;
}

What's in the struct will take precedence of what's in the template 
mixin. It's also possible to mix in several templates.

[1] http://dlang.org/spec/template-mixin.html

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list