如何使用std::relops自动提供比较运算符
how to use std::rel_ops to supply comparison operators automatically?
如何从==
和<
中获取运算符>
、>=
、<=
和!=
?
标准头<utility>
定义了一个命名空间std::rel_ops,它根据运算符==
和<
定义了上面的运算符,但我不知道如何使用它(诱使我的代码使用这样的定义:
std::sort(v.begin(), v.end(), std::greater<MyType>);
其中我定义了非成员运营商:
bool operator < (const MyType & lhs, const MyType & rhs);
bool operator == (const MyType & lhs, const MyType & rhs);
如果我#include <utility>
并指定using namespace std::rel_ops;
,编译器仍然会抱怨binary '>' : no operator found which takes a left-hand operand of type 'MyType'
。。
我会使用<boost/operators.hpp>
标头:
#include <boost/operators.hpp>
struct S : private boost::totally_ordered<S>
{
bool operator<(const S&) const { return false; }
bool operator==(const S&) const { return true; }
};
int main () {
S s;
s < s;
s > s;
s <= s;
s >= s;
s == s;
s != s;
}
或者,如果您更喜欢非会员运营商:
#include <boost/operators.hpp>
struct S : private boost::totally_ordered<S>
{
};
bool operator<(const S&, const S&) { return false; }
bool operator==(const S&, const S&) { return true; }
int main () {
S s;
s < s;
s > s;
s <= s;
s >= s;
s == s;
s != s;
}
实际上只有<
就足够了。这样做:
a == b
<=>!(a<b) && !(b<a)
a > b
<=>b < a
a <= b
<=>!(b<a)
a != b
<=>(a<b) || (b < a)
对于对称情况,以此类推。
> equals !(<=)
>= equals !(<)
<= equals == or <
!= equals !(==)
像这样的东西?
相关文章:
- 为什么比较运算符如此快速
- 布尔比较运算符是如何在C++中工作的
- 关于 std::min, std::max 中的比较运算符的混淆
- 三向比较运算符成员与非成员实现
- 标准::可选枚举的比较运算符
- C++分数混合比较运算符错误
- 不能将重载比较运算符与 Catch 测试一起使用
- 重构使用动态强制转换的 std::set 的比较运算符
- 为什么我的比较运算符不比较我的点长和双精度值?
- 高效简单的结构比较运算符
- 如何实现 Boost.Hana 结构的相等比较运算符?
- 为什么sub_match和basic_string比较运算符使用额外的字符串副本实现?
- 是否可以在C++中使用三元运算符在 if 语句中选择比较运算符?
- 在priority_queue的自定义类中重载比较运算符
- 为什么C++容器之间存在比较运算符
- 尝试使用比较运算符对对象向量进行排序
- C++复合逻辑运算符不使用比较运算符
- C++:比较运算符>和字符串文本的意外结果
- 重载对象成员的比较运算符
- 比较运算符==中的对象指针