Ada-Style Sub-Typing
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jun 2 14:44:33 PDT 2015
On 06/02/2015 01:16 PM, "Per =?UTF-8?B?Tm9yZGzDtnci?=
<per.nordlow at gmail.com>" 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.
Typedef:
http://dlang.org/phobos/std_typecons.html#.Typedef
Apparently, one needs to use its cookie feature to get what you need:
import std.typecons;
alias A = Typedef!(int, int.init, "A");
alias B = Typedef!(int, int.init, "B");
void main(string[] args)
{
A a = 11;
B b = 12;
a = b; // Fails to compile; good
}
Ali
More information about the Digitalmars-d-learn
mailing list