Chapter 12. How to Write Consistent Comparison Operators

If you wrote a new class MyClass, you might want sometimes to write expressions like this:

MyClass x, y;
  /// some code initializing x and y
  if(x < y) {
    // do something
  } else if (x == y) {
    // do something else
  }

Even if you don’t need comparison operators (<, <=, etc.) yourself, you might find that someone attempts to use your class with Standard Template Library operations that require you to define these operators. For example, if you try to sort a vector of instances of your class:

vector<MyClass> v;
v.push_back(MyClass(3));
v.push_back(MyClass(1));
v.push_back(MyClass(2));

sort(v.begin(), v.end());

an attempt to compile this code fills the screen with diagnostics that look like this:

/usr/include/c++/4.2.1/bits/stl_heap.h:121: error: no
      match for 'operator<' in '__first.
      __gnu_cxx::__normal_iterator<_Iterator, _Container>::operator+
      [with _Iterator = MyClass*, _Container = std::vector<MyClass,
      std::allocator<MyClass> >](((const ptrdiff_t&)((const
      ptrdiff_t*)(&
      __parent)))).__gnu_cxx::__normal_iterator<_Iterator,
      _Container>::operator* [with _Iterator = MyClass*, _Container =
      std::vector<MyClass, std::allocator<MyClass> >]() <
      __value'

Although this output is not easily readable by a human, after some effort one can find in that pile of information the following useful piece: no match for ‘operator<’. What the compiler is unhappy about is that the class MyClass does not define a < operator. All you have to do is add to ...

Get Safe C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.