Mankarse Mankarse - 4 years ago 124
C++ Question

Idiomatic use of std::rel_ops

What is the preferred method of using std::rel_ops to add the full set of relational operators to a class?

This documentation suggests a

using namespace std::rel_ops
, but this seems to be deeply flawed, as it would mean that including the header for the class implemented in this way would also add full relational operators to all other classes with a defined operator< and operator==, even if that was not desired. This has the potential to change the meaning of code in surprising ways.

As a side note - I have been using Boost.Operators to do this, but I am still curious about the standard library.

Answer Source

I think that the preferred technique is not to use std::rel_ops at all. The technique used in boost::operator (link) seems to be the usual solution.


#include "boost/operators.hpp"

class SomeClass : private boost::equivalent<SomeClass>, boost::totally_ordered<SomeClass>
    bool operator<(const SomeClass &rhs) const
        return someNumber < rhs.someNumber;
    int someNumber;

int main()
    SomeClass a, b;
    a < b;
    a > b;
    a <= b;
    a >= b;
    a == b;
    a != b;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download