[Issue 16657] alias this interacts with generated opCmp and opEquals
via Digitalmars-d-bugs
digitalmars-d-bugs at puremagic.com
Sat May 13 12:23:00 PDT 2017
https://issues.dlang.org/show_bug.cgi?id=16657
--- Comment #3 from Andrei Alexandrescu <andrei at erdani.com> ---
It seems a case can be made for either behavior.
* The "alias this" feature emulates subtyping of the kind typically achieved by
class inheritance. If that is the default behavior to emulate, the current
behavior is up to the task. Consider a moral equivalent:
class A {
int x;
this(int x) { this.x = x; }
override bool opEquals(Object rhs) { return x == (cast(A) rhs).x; }
}
class B : A {
this(int x, int y) { super(x); this.y = y; }
int y;
}
void main() {
assert(new A(1) == new B(1, 2)); // pass
}
This "slices" B for the purpose of comparison.
* Yes, "alias this" does emulate subtyping, but we have an autogenerated
opEquals for every struct. Why should there be the case that such generation
automatically disappears in the case "alias this" is used?
* Another argument for changing behaviors has to do with practicality. Even
though a subtyping-based argument can be created in favor of preserving
existing compatibility, a better argument is that in fact the _current_ OOP
behavior (illustrated by the example with classes above) is incorrect and
error-prone. There's good evidence for that (e.g.
http://stackoverflow.com/questions/12239344/why-should-i-not-use-equals-with-inheritance
of many examples). The theoretical underpinnings for correctly defining
comparison in conjunction with subtyping is bounded quantification
(https://en.wikipedia.org/wiki/Bounded_quantification).
The short of it all is the current behavior can and should be improved.
Changing behavior silently is not a good choice, so we should probably issue a
warning when the situation occurs. The warning can be extinguished by defining
opEquals explicitly. With time the warning becomes an error following a
schedule similar to deprecation.
--
More information about the Digitalmars-d-bugs
mailing list