Ada-Style Sub-Typing

Charles Hixson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 6 16:08:43 PDT 2015


It's not totally convenient, but what I'm currently using is a slightly 
less elaborate struct:
struct    A
{    int    v;    }

Since all I'm creating is an isolated type, the private stuff isn't 
needed.  If I wanted to get fancy I could start implementing 
operations.  Comparison is free, as sturcts of the same type are, by 
default, compared via a bit match.  This, however, doesn't give you less 
than, greater than, etc. I think you need to implement those, almost 
certainly if you want to use anything but unsigned comparison.

OTOH, if you do an alias this, then I'm not sure you maintain type 
isolation.  I think that will auto-convert to the type of the variable.  
(I haven't checked this...so perhaps I'm just being pessimistic/optimistic.)

Consider what purpose declaring the internal variable to be private 
serves.  Remember that structs are copied rather than passed by 
reference, and I think you'll decide it doesn't really serve any purpose.

On 06/02/2015 01:16 PM, via Digitalmars-d-learn wrote:
> Is there some elegant way of creating "isolated" types in D similar to 
> the semantics of `subtype` in Ada.
>
> Something like this
>
> struct A
> {
>     this(int value) { this._value = value; }
>     private int _value;
>     alias _value this;
> }
>
> struct B
> {
>     this(int value) { this._value = value; }
>     private int _value;
>     alias _value this;
> }
>
> void main(string[] args)
> {
>     A a = 11;
>     B b = 12;
>     a = b;
> }
>
> except that
>
> the final statement should error.
>



More information about the Digitalmars-d-learn mailing list