【C++】std的subnamespace rel_ops

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;)


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值