如何在C ++中实现3 <= X <= 10? [英] How to implement 3 &lt;= X &lt;= 10 in C++?

查看:147
本文介绍了如何在C ++中实现3 <= X <= 10?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要能写

if (3 <= X <= 10)
{

}
else if (20 < X < 100) 
{ //...etc

在C ++中,并正确评估。我知道你可以在Python中这样做,我认为这是一个非常可读的方式来表达一个条件。

in C++ and have it evaluate correctly. I know you can do this in Python and I think it's a very readable way to express a conditional.

我不想写:

if (3 <= X && X <= 10) //etc.

我如何在C ++中做到这一点?是否可以?什么会重载操作符看起来像? 如果没有,您能解释为什么不可能

How can I do this in C++? Is it possible? What would overloading the operators look like? If not, could you explain why it's not possible?

推荐答案

[UPDATE]

过了一段时间后,我发现一个想法,

After a while I come to an idea which even does not look totally crazy ;)

我在ideone 制作了工作范例

您需要从第一个元素开始:

You need to start with wrapping of the first element:

int main() {
   int x = 134, y = 14;
   if (IntComp(7) <= x <= 134)
   {
       std::cout << "Hello ";
   } 
   if (IntComp(134) > y > 12)
   {
       std::cout << "world!";
   } 
}

这里的魔力:

class IntComp {
public:
   IntComp(int x, bool result = true) : value(x), result(result) {}
   IntComp operator <= (int x) const
   {
       return IntComp(x, result && value <= x);
   }
   IntComp operator > (int x) const
   {
       return IntComp(x, result && value > x);
   }
   operator bool() const { return result; }
private:
   int value;
   bool result;
};

这篇关于如何在C ++中实现3 <= X <= 10?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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