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 。
可能的实现
| 版本一 | 
|---|
| namespace rel_ops { template< class T > bool operator!=( const T& lhs, const T& rhs ) { return !(lhs == rhs); } } | 
| 版本二 | 
| namespace rel_ops { template< class T > bool operator>( const T& lhs, const T& rhs ) { return rhs < lhs; } } | 
| 版本三 | 
| namespace rel_ops { template< class T > bool operator<=( const T& lhs, const T& rhs ) { return !(rhs < lhs); } } | 
| 版本四 | 
| 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; std::cout << "not equal? : " << (f1 != f2) << '\n'; std::cout << "greater? : " << (f1 > f2) << '\n'; std::cout << "less equal? : " << (f1 <= f2) << '\n'; std::cout << "greater equal? : " << (f1 >= f2) << '\n'; }
输出:
not equal? : true greater? : false less equal? : true greater equal? : false
 
	