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

来自cppreference.com
< cpp‎ | utility
 
 
工具库
通用工具
关系运算符 (C++20 弃用)
rel_ops::operator!=rel_ops::operator>
  
rel_ops::operator<=rel_ops::operator>=
整数比较函数
(C++20)(C++20)(C++20)  
(C++20)
交换类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)


 
在标头 <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