hackjutsu hackjutsu -4 years ago 60
C++ Question

Use only < comparisons in Generic Programming

I am reading the "Templates and Generic Programming" part in C++ Primer(5th Edition) but I got confused by some of the stuff there.

When talking about "Writing Type-Independent Code" at P655 & P656, the author stated that
"The tests in the body use only < comparisons " , because "by writing the code using only the < operator, we reduce the requirements on types that can be used with our compare function. Those types must support <, but they need not also support >." .

Are there any types that support < but not > ? If so, why < has the superiority over > ? I have searched on Google for some time but I failed to get the answer. Could anybody give me some examples or some referral links?

Answer Source

If so, why < has the superiority over >?

Mere convention. The character '<' comes first in ASCII, and less-than over a partially-ordered set is a primitive from which the comparisons may be constructed (i.e., the set is partitioned into equivalence groups).

If we have a, b, and operator <:

  • a < b if operator <( a, b )
  • a > b if operator <( b, a )
  • a ≤ b if ! operator <( b, a )
  • a = b if ! operator <( a, b ) && ! operator <( b, a )
  • etc.

C++ has a number of such conventions which are used to describe how types behave. These are often called concepts, and an upcoming language extension, capital-C Concepts, will allow you to query and specify such things as whether the less-than operator defines a partial ordering.

Are there any types that support < but not >?

Yes, many. The convention is to define operator < and then forget about > because it would be redundant. You can use something like std::relops to automatically define > in terms of <, but overall it's easier just to avoid writing the > operator in the first place.

All the parts of the standard library that depend on ordering, such as std::sort and std::map, will never use >.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download