ProtoObject and comparison for equality and ordering

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed May 15 16:48:50 UTC 2019


On Wednesday, May 15, 2019 10:13:47 AM MDT H. S. Teoh via Digitalmars-d 
wrote:
> On Wed, May 15, 2019 at 11:14:17AM -0400, Andrei Alexandrescu via 
Digitalmars-d wrote:
> > One thing that bothers me is inheritance. It seems to me most of the
> > time just inheriting opCmp and opEquals does not work - they'd need to
> > be overridden to account for the added state. However, sometimes they
> > _do_ just work. So I'm in two minds on whether inheriting but not
> > overloading those two should be an error or not.
>
> How would you enforce it, though?  If we go the compile-time
> introspection route, that means user base classes that define opCmp can
> define whatever they want, including allowing derived classes to simply
> inherit base class opCmp.  It wouldn't be ProtoObject's responsibility
> to enforce any policies concerning opCmp -- it'd be up to the user to
> get it right.

It wouldn't have anything to do wtih ProtoObject. Presumably, if a class
defined opCmp but not opEquals, it would be an error, and if a base class
defined opCmp, and the derived class defined either opEquals or opCmp, it
would be an error if it hadn't also defined the other.

We could also choose to do something similar to what we do when a derived
class overloads a base class function and involve alias. So, a derived class
could either override neither opEquals nor opCmp, override both, or override
one and provide an alias to the base class function for the other. I suppose
that it could also alias both, though that would be rather pointless.

As to whether we _should_ make it an error to override one but not the
other... I don't know. It seems highly unlikely that it would make sense to
override one and not the other if any behavioral changes are being made
(though you could certainly make one do something like log without caring
about the other), and the risk of bugs when you override one but not the
other would be high. So, requiring that either both or neither be overridden
would probably be worth it even if it were annoying in some cases -
especially if an alias were enough in those cases where you didn't really
want to override both.

Another consideration is that a base class could define opEquals without
defining opCpm while a derived class did define opCmp. And in that case, the
odds are much higher that overriding opEquals is unnecessary - though
requiring at least an alias could be worth it given the risk of bugs.
Certainly, it's something to think about.

toHash has similar issues if both it and opEquals are defined, though it
makes far more sense to override opEquals without overriding toHash than it
makes to override opEquals without overriding opCmp.

- Jonathan M Davis





More information about the Digitalmars-d mailing list