名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | 工具
 
 
工具庫
通用工具
關係運算符 (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) 如果 lhsrhs 不相等,則返回 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