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&);
}
This namespace declares template functions for four relational operators (!=,>, <=, and >=), deriving their behavior from operator== (for !=) and from operator< (for >,<=, and >=):
此命名空间声明了4个关系操作符的模板函数(!= > <= >=),利用了操作符=(为!=服务)和<(为> <= >=)服务。
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); }
}
利用两个关系操作符便 可以得到6个,只需要using namespace rel_ops; 即可。
// 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;
//虽然类中只重载了==和<两个关系操作符,但使用命名空间rel_ops后便可以得到6个。
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;
}
另外为什么rel_ops要做为std的子空间?
namespace std {
namespace rel_ops {
template <class T>
inline bool operator!= (const T& x, const T& y) {
return !(x == y);
bool operator== (const X& x) const;
bool operator< (const X& x) const;
...
}
}
};
Note that these operators are defined in a subnamespace of std, called rel_ops. The reason
that they are in a separate namespace is so that users who define their own relational operators
in the global namespace won't clash even if they made all identifiers of namespace std global by
using a general using directive:(避免了与用户自定义的关系操作符发生冲突,即使使用了using namespace std;)