三元比较运算符重载 [英] Ternary comparison operator overloading

查看:167
本文介绍了三元比较运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实现三元比较运算符以确定例如 a 的布尔值, b <解决方案:
当对比较进行编码时,返回类型为:

一个比较对象可以链接额外的比较,但是可以隐式转换为 bool 。这甚至可以使用未使用此意图编码的类型,只需通过手动将它们转换为比较类型。



实现:

 模板< class T& 
类比较{
const bool result;
const T&持续;
public:
比较(const T& l,bool r = true):result(r),last(l){}
operator bool()const {return result;}
比较运算符<(const T& rhs)const {return比较(rhs,(result&&& last< rhs));}
比较运算符< rhs,(result&&& last> rhs));}
比较运算符>(const T& rhs)const {return comparison b $ b比较运算符> =(const T& rhs)const {return comparison(rhs,(result&& last> = rhs));}
};

一个有用的示例:

  #include< iostream> 
int main(){
//用int
测试链接的比较std :: cout<< (比较< int>(0)< 1< 2)< '\\\
';
std :: cout<< (比较< int>(0)< 1 2)< '\\\
';
std :: cout<< (比较< int>(0)> 1< 2)< '\\\
';
std :: cout<< (比较< int>(0)> 1> 2)< '\\\
';
}

输出:



<$ pre> 1
0
0
0

注意:这是由 Mooing Duck 创建的,可以找到一个编译更健壮的示例上 http://ideone.com/awrmK


How would one implement a ternary comparison operator to determine, for example, the boolean value of a < b < c?

解决方案

Solution: When coding a comparison, have the return type be a comparison object that can chain additional comparisons, but is implicitly convertible to a bool. This can even (kind of) work with types that weren't coded with this intent, simply by casting them to the comparison type manually.

Implementation:

template<class T>
class comparison {
  const bool result;
  const T& last;
public:
  comparison(const T& l, bool r=true) :result(r), last(l) {}
  operator bool() const {return result;}
  comparison operator<(const T& rhs) const {return comparison(rhs, (result && last<rhs));}
  comparison operator<=(const T& rhs) const {return comparison(rhs, (result && last<=rhs));}
  comparison operator>(const T& rhs) const {return comparison(rhs, (result && last>rhs));}
  comparison operator>=(const T& rhs) const {return comparison(rhs, (result && last>=rhs));}
};

A useful example:

#include <iostream>
int main() {
  //testing of chained comparisons with int
  std::cout << (comparison<int>(0) < 1 < 2) << '\n';
  std::cout << (comparison<int>(0) < 1 > 2) << '\n';
  std::cout << (comparison<int>(0) > 1 < 2) << '\n';
  std::cout << (comparison<int>(0) > 1 > 2) << '\n';
}

Output:

1
0
0
0

Note: This was created by Mooing Duck, and a compiled, more robust example can be found on http://ideone.com/awrmK

这篇关于三元比较运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆