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 nam
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.
Example:
#include "boost/operators.hpp"
class SomeClass : private boost::equivalent<SomeClass>, boost::totally_ordered<SomeClass>
{
public:
bool operator<(const SomeClass &rhs) const
{
return someNumber < rhs.someNumber;
}
private:
int someNumber;
};
int main()
{
SomeClass a, b;
a < b;
a > b;
a <= b;
a >= b;
a == b;
a != b;
}
The problem with adding the rel_ops namespace, regardless of whether you do it with a manual using namespace rel_ops;
or whether you do it automatically as described in the answer by @bames53 is that adding the namespace can have unanticipated side effects on portions of your code. I found this myself just recently as I had been using the @bames53 solution for some time, but when I changed one of my container based operations to use a reverse_iterator instead of an iterator (within a multimap but I suspect it would be the same for any of the standard containers), suddenly I was getting compile errors when using != to compare two iterators. Ultimately I tracked it down to the fact that the code included the rel_ops namespace which was interfering with how reverse_iterators are defined.
Using boost would be a way to solve it, but as mentioned by @Tom not everyone is willing to use boost, myself included. So I implemented my own class to solve the problem, which I suspect is also how boost does it, but I didn't check the boost libraries to see.
Specifically, I have the following structure defined:
template <class T>
struct add_rel_ops {
inline bool operator!=(const T& t) const noexcept {
const T* self = static_cast<const T*>(this);
return !(*self == t);
}
inline bool operator<=(const T& t) const noexcept {
const T* self = static_cast<const T*>(this);
return (*self < t || *self == t);
}
inline bool operator>(const T& t) const noexcept {
const T* self = static_cast<const T*>(this);
return (!(*self == t) && !(*self < t));
}
inline bool operator>=(const T& t) const noexcept {
const T* self = static_cast<const T*>(this);
return !(*self < t);
}
};
To use this, when you define your class, say MyClass, you can inherit from this one to add the "missing" operators. Of course you need to define the == and < operators within MyClass (not shown below).
class MyClass : public add_rel_ops<MyClass> {
...stuff...
};
It is important that you include MyClass
as the template argument. If you were to include a different class, say MyOtherClass
, the static_cast
would be almost certain to give you problems.
Note that my solution is assuming that the ==
and <
operators are defined as const noexcept
which is one of the requirements of my personal coding standards. If your standards are different, you would need to modify add_rel_ops accordingly.
In addition, if you are bothered by the use of static_cast
, you can change them to be a dynamic_cast
by adding
virtual ~add_rel_ops() noexcept = default;
to the add_rel_ops class in order to make it a virtual class. Of course, that will also force MyClass
to be a virtual class which is why I do not take that approach.
The way operator overloads for user defined classes was meant to work is via argument dependent lookup. ADL allows programs and libraries to avoid cluttering up the global namespace with operator overloads, but still allow convenient use of the operators; That is, without explicit namespace qualification, which is not possible to do with the infix operator syntax a + b
and would instead require normal function syntax your_namespace::operator+ (a, b)
.
ADL, however, doesn't just search everywhere for any possible operator overload. ADL is restricted to look only at 'associated' classes and namespaces. The problem with std::rel_ops
is that, as specified, this namespace can never be an associated namespace of any class defined outside the standard library, and therefore ADL cannot work with such user defined types.
However, if you're willing to cheat you can make std::rel_ops
work.
Associated namespaces are defined in C++11 3.4.2 [basic.lookup.argdep] /2. For our purposes the important fact is that the namespace of which a base class is a member is an associated namespace of the inheriting class, and thus ADL will check those namespaces for appropriate functions.
So, if the following:
#include <utility> // rel_ops
namespace std { namespace rel_ops { struct make_rel_ops_work {}; } }
were to (somehow) find its way into a translation unit, then on supported implementations (see next section) you could then define your own class types like so:
namespace N {
// inherit from make_rel_ops_work so that std::rel_ops is an associated namespace for ADL
struct S : private std::rel_ops::make_rel_ops_work {};
bool operator== (S const &lhs, S const &rhs) { return true; }
bool operator< (S const &lhs, S const &rhs) { return false; }
}
And then ADL would work for your class type and would find the operators in std::rel_ops
.
#include "S.h"
#include <functional> // greater
int main()
{
N::S a, b;
a >= b; // okay
std::greater<N::s>()(a, b); // okay
}
Of course adding make_rel_ops_work
yourself technically causes the program to have undefined behavior because C++ does not allow user programs to add declarations to std
. As an example of how that actually does matter and why, if you do this, you may want to go to the trouble of verifying that your implementation does in fact work properly with this addition, consider:
Above I show a declaration of make_rel_ops_work
that follows #include <utility>
. One might naively expect that including this here doesn't matter and that as long as the header is included sometime prior to the use of the operator overloads, then ADL will work. The spec of course makes no such guarantee and there are actual implementations where that is not the case.
clang with libc++, due to libc++'s use of inline namespaces, will (IIUC) consider that declaration of make_rel_ops_work
to be in a distinct namespace from the namespace containing the <utility>
operator overloads unless <utility>
's declaration of std::rel_ops
comes first. This is because, technically, std::__1::rel_ops
and std::rel_ops
are distinct namespaces even if std::__1
is an inline namespace. But if clang sees that the original namespace declaration for rel_ops
is in an inline namespace __1
, then it will treat a namespace std { namespace rel_ops {
declaration as extending std::__1::rel_ops
rather than as a new namespace.
I believe this namespace extension behavior is a clang extension rather than specified by C++, so you may not even be able to rely on this in other implementations. In particular gcc does not behave this way, but fortunately libstdc++ doesn't use inline namespaces. If you don't want to rely on this extension then for clang/libc++ you can write:
#include <__config>
_LIBCPP_BEGIN_NAMESPACE_STD
namespace rel_ops { struct make_rel_ops_work {}; }
_LIBCPP_END_NAMESPACE_STD
but obviously then you'll need implementations for other libraries you use. My simpler declaration of make_rel_ops_work
works for clang3.2/libc++, gcc4.7.3/libstdc++, and VS2012.
It's not the nicest, but you can use using namespace std::rel_ops
as an implementation detail for implementing the comparison operators on your type. For example:
template <typename T>
struct MyType
{
T value;
friend bool operator<(MyType const& lhs, MyType const& rhs)
{
// The type must define `operator<`; std::rel_ops doesn't do that
return lhs.value < rhs.value;
}
friend bool operator<=(MyType const& lhs, MyType const& rhs)
{
using namespace std::rel_ops;
return lhs.value <= rhs.value;
}
// ... all the other comparison operators
};
By using using namespace std::rel_ops;
, we allow ADL to lookup operator<=
if it is defined for the type, but fall back onto the one defined in std::rel_ops
otherwise.
This is still a pain, though, as you still have to write a function for each of the comparison operators.