c++中的工具(二):自动生成比较操作符

在C++头文件<utility>中,定义了一个命名空间rel_ops,其中专门存放了四个不同的比较操作符:>=<=>!=。代码实现如下:

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 !(y < x);
        }

        template<class T>
        inline bool operator<=(const T&x, const T&y){
            return !(x < y);
        }
}
        

即实现上述四个比较运算符,只需要我们实现<和==,其他四个可自动生成。

在程序中使用 using namespace std::rel_ops; 即可自动生成这四个运算符。

posted @ 2020-01-31 13:22  mindulmindul  阅读(262)  评论(0编辑  收藏  举报