std::rel_ops::operator!=,>,<=,>=
來自 cppreference.com
在標頭檔案 <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