Subtyping

struct can't inherit from other structs. But for those poor structs D provides another great means to extend their functionality: subtyping.

A struct type can define one of its members as alias this:

struct SafeInt {
    private int theInt;
    alias theInt this;
}

Any function or operation on SafeInt that can't be handled by the type itself will be forwarded to the alias thised member. From the outside SafeInt then looks like a normal integer.

This allows extending other types with new functionality but with zero overhead in terms of memory or runtime. The compiler makes sure to do the right thing when accessing the alias this member.

alias this work with classes too.

rdmd playground.d