Often times I find myself using std::pair to define logical groupings of two related quantities as function arguments/return values. Some examples: row/col, tag/value, etc.
You can use some standard utility templates that help define the relation operators.
#include <utility>
http://www.sgi.com/tech/stl/operators.html
The requirement for operator!= is that x == y is a valid expression
The requirement for operator> is that y < x is a valid expression
The requirement for operator<= is that y < x is a valid expression
The requirement for operator>= is that x < y is a valid expression
So basically it will automatically generate the other operators give < and == all you have to do is include <utility>
Unfortunately strong typedefs will not make it into C++0x, it has been given the classification of Not ready for C++0x, but open to resubmit in future.
A coworker pointed me to two possible solutions:
Using boost strong typedef as an improved version of the typedef. I'd never heard of this before, and it doesn't seem to really be part of any sub-library, just kind of floating.
Using a macro to generate the code needed for the different operators. This way I wouldn't have to explicitly write anything on a per definition level, just do something like DEFINE_PAIR_TYPE(Position, int, int, row, col);
. This is probably closest to what I'm looking for, but it still feels kind of evil compared to some of the solutions presented by others.
This is what Boost.Tuple was made for.
But you should probably be using std::tuple now...
There's also the Boost::Operators library to automatically generate operator code. It's similar to the SGI library that Martin York suggested, but might be more portable.
You can still reuse the pair
functionality by forwarding to it:
bool operator< ( const Position &a, const Position &b )
{
return
std::make_pair( a.row, a.col ) < std::make_pair( b.row, b.col );
}
Although you still end up with doing this for every operatory you need...