| rel_ops | namespace |
namespace rel_ops {
template <class T> bool operator!= (const T&, const T&);
template <class T> bool operator> (const T&, const T&);
template <class T> bool operator<= (const T&, const T&);
template <class T> bool operator>= (const T&, const T&);
} |
<utility> |
Relational Operators
This namespace declares template functions for four relational operators (!=,>, <=, and >=), deriving their behavior from operator== (for !=) and from opertator< (for >,<=, and >=):
namespace rel_ops { template <class T> bool operator!= (const T& x, const T& y) { return !(x==y); } template <class T> bool operator> (const T& x, const T& y) { return y<x; } template <class T> bool operator<= (const T& x, const T& y) { return !(y<x); } template <class T> bool operator>= (const T& x, const T& y) { return !(x<y); } } |
This avoids the necessity to declare all six relational operators for every complete type; By defining just two: operator== and operator<, and importing this namespace, all six operators will be defined for the type.
Still, because non-template functions take precedence over template functions, any of these operators may be defined with a different behavior for a specific type, even with rel_ops being used.
Template parameters
- T
- For operator!=, the type shall be EqualityComparable.
A type is EqualityComparable when it supports operator== operations that follow the typical reflexive, symmetric and transitive properties of equalities.For operator>, operator<=, and perator>=, the type must be LessThanComparable.
A type is LessThanComparable when it supports operator< operations that define a valid strict weak ordering relation.
Example
// rel_ops example: #include <iostream> #include <utility> #include <cmath> using namespace std; class vector2d { public: double x,y; vector2d (double px,double py): x(px), y(py) {} double length () const {return sqrt(x*x+y*y);} bool operator==(const vector2d& rhs) const {return length()==rhs.length();} bool operator< (const vector2d& rhs) const {return length()< rhs.length();} }; using namespace rel_ops; int main () { vector2d a (10,10); // length=14.14 vector2d b (15,5); // length=15.81 cout << boolalpha; cout << "(a<b) is " << (a<b) << "\n"; cout << "(a>b) is " << (a>b) << "\n"; return 0; } |
Output:
(a<b) is true |
Because we used rel_ops, all types for which operator< is defined (like vector2d) also have operator>.
See also
| utility | Utility components (header) |
