Reputation: 146910
I've seen that, if you have operator<
, you can implement, say, operator>=
as !(a < b)
. However, when I went to the C++ Committee in Bristol, they said that you can implement all the comparison operators this way. Particularly, when considering types which have non-trivial comparison operators (consider an arbitrarily long string, especially if this is Unicode), this can be done with only one call to operator<
. I cannot conceive of how this could be done.
How can I implement operator>
and operator<=
with just one call to operator<
and none to the other comparison operators?
Upvotes: 14
Views: 2141
Reputation: 42554
a > b == b < a
a <= b == !(b < a)
a >= b == !(a < b)
It's even possible to implement equality in terms of less than (Kind of abusing my meta-syntax here):
(a == b) == (!(a < b) && !(b < a))
(a != b) == (a < b || b < a)
Although I wouldn't suggest doing so in practice, since it requires two comparisons and can generally be implemented more efficiently directly.
Upvotes: 20