Subtypes with tighter constraints
Neia Neutuladh
neia at ikeran.org
Tue Jan 1 22:02:40 UTC 2019
On Tue, 01 Jan 2019 14:05:43 +0000, Victor Porton wrote:
> In Ada2012 there are "subtypes". Subtypes can have tighter constraints
> (such as type invariants) than their base types.
>
> I have a struct X in D. Is it possible to define a type equivalent to X
> except that having tighter invariants?
In D, structs don't participate in inheritance. Classes do, but invariants
aren't inherited; they're specific to the class in which the function is
defined. (Which is probably a bug and I filed https://issues.dlang.org/
show_bug.cgi?id=19537.)
I see three ways to make this work today:
1. Use alias this to wrap the struct. Add invariants that deal with the
wrapped struct's fields.
2. Use compile-time reflection to copy the fields over, then manually copy
the invariants over and add more.
3. Use a class. Define a virtual function like 'doInvariant()`. Call it
from the base class's invariant{} block.
> As I understand if I derive Y from X, then it is no more X; that is I
> cannot use X (even provided it matches Y invariants) where I need Y. So
> in D it is impossible, right?
With classes, a derived class instance can be used anywhere you expect a
base class instance. The reverse is not true.
More information about the Digitalmars-d-learn
mailing list