std::rel_ops::operator!=,>,<=,>=
来自cppreference.com
| 在标头 <utility> 定义
|
||
| (1) | (C++20 弃用) | |
| (2) | (C++20 弃用) | |
| (3) | (C++20 弃用) | |
| (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<=> 而被弃用。
示例
Run this code
#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