ProtoObject and comparison for equality and ordering

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue May 14 21:47:18 UTC 2019


On Tuesday, May 14, 2019 3:21:56 PM MDT Mike Franklin via Digitalmars-d 
wrote:
> On Tuesday, 14 May 2019 at 20:36:08 UTC, Eduard Staniloiu wrote:
> > Should `opCmp` return a float?
> >
> > The reason: when we attempt to compare two types that aren't
> > comparable (an unordered relationship) we can return float.NaN.
> > Thus we can differentiate between a valid -1, 0, 1 and an
> > invalid float.NaN comparison.
>
> Thinking about this a little more, why would the compiler even
> allow comparing two types that aren't comparable?  Shouldn't that
> be a compiler error?

The issue is being able to reproduce the behavior of comparing floating
point types when one of them is NaN. That design of floating point
comparison does make some sense with regards to floating points but
seriously complicates things for overloading opCmp. In general, it really
doesn't make sense to return anything other than an integral value, but if
you want to be able to create a type that wraps floats (e.g. Nullable!float)
or emulates them in some manner, then you need more flexibility.

Given that, it's probably sufficient if the spec requires that the type be
comparable with -1, 0, and 1 with the comparison operators being generated
from that rather than requiring a specific type (which IIRC is more or less
what the spec currently says for structs). Even if a class returned some
weird type that took int or float for its opCmp so that you when was
compared against -1, 0, and/or 1 to generate a comparison operator, I don't
_think_ that you could really do anything with that ultimately other than
just get weird results for the comparison.

As long as the code using the comparison operators with a class object is
templated, it really shouldn't matter what the exact signature is so long as
it compiles with the right types - just like with structs. And if the code
isn't templated, then it would likely be operating on whatever the base
class was that implemented opCmp in that particular class hierarchy. Either
way, I don't see any reason for the rules for the signature of opCmp with
classes to be any different from opCmp and structs aside from where a
derived class is restricted by how its base class declared it.

- Jonathan M Davis





More information about the Digitalmars-d mailing list