Namespaces
Variants

std::rel_ops:: operator!=,>,<=,>=

From cppreference.net
Utilities library
General utilities
Relational operators (deprecated in C++20)
rel_ops::operator!= rel_ops::operator>
rel_ops::operator<= rel_ops::operator>=
Integer comparison functions
(C++20) (C++20) (C++20)
(C++20)
Swap and type operations
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)


定义于头文件 <utility>
template < class T >
bool operator ! = ( const T & lhs, const T & rhs ) ;
(1) (C++20 起弃用)
template < class T >
bool operator > ( const T & lhs, const T & rhs ) ;
(2) (C++20 起弃用)
template < class T >
bool operator <= ( const T & lhs, const T & rhs ) ;
(3) (C++20 起弃用)
template < class T >
bool operator >= ( const T & lhs, const T & rhs ) ;
(4) (C++20 起弃用)

给定用户为类型 T 对象自定义的 operator == operator < ,实现其他比较运算符的常规语义。

1) 基于 operator == 实现 operator ! =
2) 基于 operator < 实现 operator >
3) 基于 operator < 实现 operator <=
4) 基于 operator < 实现 operator >=

目录

参数

lhs - 左操作数
rhs - 右操作数

返回值

1) lhs 不等于 rhs 时返回 true
2) lhs 大于 rhs 时返回 true
3) lhs 小于或等于 rhs 时返回 true
4) lhs 大于或等于 rhs 时返回 true

可能的实现

(1) operator!=
namespace rel_ops
{
    template<class T>
    bool operator!=(const T& lhs, const T& rhs)
    {
        return !(lhs == rhs);
    }
}
(2) operator>
namespace rel_ops
{
    template<class T>
    bool operator>(const T& lhs, const T& rhs)
    {
        return rhs < lhs;
    }
}
(3) operator<=
namespace rel_ops
{
    template<class T>
    bool operator<=(const T& lhs, const T& rhs)
    {
        return !(rhs < lhs);
    }
}
(4) operator>=
namespace rel_ops
{
    template<class T>
    bool operator>=(const T& lhs, const T& rhs)
    {
        return !(lhs < rhs);
    }
}

注释

Boost.operators 提供了比 std::rel_ops 更灵活的选择方案。

截至 C++20, std::rel_ops 已被弃用,建议改用 operator<=>

示例

#include <iostream>
#include <utility>
struct Foo
{
    int n;
};
bool operator==(const Foo& lhs, const Foo& rhs)
{
    return lhs.n == rhs.n;
}
bool operator<(const Foo& lhs, const Foo& rhs)
{
    return lhs.n < rhs.n;
}
int main()
{
    Foo f1 = {1};
    Foo f2 = {2};
    using namespace std::rel_ops;
    std::cout << std::boolalpha
              << "{1} != {2} : " << (f1 != f2) << '\n'
              << "{1} >  {2} : " << (f1 >  f2) << '\n'
              << "{1} <= {2} : " << (f1 <= f2) << '\n'
              << "{1} >= {2} : " << (f1 >= f2) << '\n';
}

输出:

{1} != {2} : true
{1} >  {2} : false
{1} <= {2} : true
{1} >= {2} : false