在C++中如果要定义比较操作符,可以只定义<和==操作符,然后利用using namespace std::rel_ops使用定义在<utility>中的四个辅助性的“比较操作符”(分别是!=,>,<=,>=)。
这四个函数的定义如下:
namespace std {
namespace rel_ops {
template<class T>
inline bool operator> (const T& x, const T& y) {
return !(x==y);
}
template <class T>
inline bool operator<= (const T& x, const T& y) {
return !(y<x);
}
template <class T>
inline bool operator!= (const T& x, const T& y) {
return !(x==y);
}
template <class T>
inline bool operator>= (const T& x, const T& y) {
return !(x<y);
}
} // namespace rel_ops
} // namespace std
实际这四个辅助的比较操作符都是利用了已经定义好的==与<操作符。
使用这些辅助的比较操作符可以避免写一些不必要的代码。
笔记 《C++标准程序库》 P69