Subtypes with tighter constraints
Alex
sascha.orlov at gmail.com
Tue Jan 1 19:33:15 UTC 2019
On Tuesday, 1 January 2019 at 14:05:43 UTC, 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?
>
> As I understand if I derive Y from X, then it is no more X;
1. As Ada is strongly typed, this is the same there, no?
2. You cannot derive structs in D. Therefore, I assume, that you
meant that X and Y are classes.
> that is I cannot use X (even provided it matches Y invariants)
> where I need Y. So in D it is impossible, right?
It is possible, as invariants are inherited implicitly, see
https://dlang.org/spec/contracts.html#Invariants
paragraph 9.
´´´
import std.experimental.all;
void main()
{
auto x = new X();
auto y = new Y();
x.d = 0.0;
y.d = 1.0;
x.fun;
y.fun;
}
class X
{
double d;
invariant
{
assert(!d.isNaN);
}
}
class Y : X
{
invariant
{
assert(d > 0);
}
}
void fun(T)(T t)
{
assert(t);
}
´´´
More information about the Digitalmars-d-learn
mailing list