|
Boost : |
From: Christopher Eltschka (celtschk_at_[hidden])
Date: 2006-07-13 11:30:08
Hi,
I have a very simple header to simplify use of std::rel_ops with user
defined classes, and I thought it might be interesting for inclusion in
boost. It seems to work perfectly on gcc 4.0.2 20050901 (prerelease)
(SUSE Linux), and I believe it's standard conforming. I haven't checked
it with any other compiler, though.
The usage is simple: You just write (with my current header, which of
course would have to be adapted for boost):
----------------------------------------------------------------------
#include "relops.h"
class MyClass: rel::ops
// doesn't matter if you use public or private inheritance
{
// ...
};
bool operator<(MyClass const&, MyClass const&) { /* ... */ }
bool operator==(MyClass const&, MyClass const&) { /* ... */ }
// now you can use all comparison operators:
int main()
{
MyClass a, b;
bool b = (a > b) // uses std::rel_ops::operator>
}
----------------------------------------------------------------------
operator< and operator== of course can be defined anywhere the
std::rel_ops operators will find them (e.g. they could be defined as
class members instead).
The header is obviously too simple to warrant its own boost library, but
I could imagine it to be included e.g. in Boost.Utility. Alternatively
it could be extended to support other typical operator implementations
not covered by the standard, e.g. defining operator@ in terms of operator@=.
Here's the actual code of the header:
----------------------------------------------------------------------
#ifndef RELOPS_H_INC
#define RELOPS_H_INC
#include <utility>
namespace rel
{
using std::rel_ops::operator!=;
using std::rel_ops::operator>;
using std::rel_ops::operator>=;
using std::rel_ops::operator<=;
class ops {};
}
#endif
----------------------------------------------------------------------
The trick is that by deriving from class rel::ops, you get the namespace
rel looked into during Koenig lookup for function calls, esp. operators,
involving your class type. Now, in namespace rel, the operators from
std::rel_ops are found due to the explicit using declarations (obviously
it would have been easier just to add class ops into std::rel_ops, but
that's unfortunately prohibited by the standard). Deriving from class
ops doesn't bring anything into your class than the additional Koenig
lookup target, and with empty base class optimization it shouldn't
affect your class otherwise as well.
So what do you think?
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk