命名空间
变体
操作

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

来自 cppreference.cn
< 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 中已弃用)

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

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