2012-06-13 52 views
2

一个将如何实现三元比较运算符来确定,例如,a < b < c布尔值?三元比较运算符重载

+2

呃,你张贴了这个问题,所以您可以张贴别人的答案..? – ildjarn

+6

我认为这将是在C++更可读的写类似'范围(A,C)。载(B)'。 –

+1

@ildjarn是的,但是这是张贴在休息室,我问权限张贴在主要网站上。 – Drise

回答

6

解决方案: 编码比较时,返回类型应为comparison对象,可以链接附加比较,但可以隐式转换为bool。这甚至(种)可以与没有这种意图的编码,只需通过他们铸造手动comparison型工种。

实现:

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));} 
}; 

一个有用的例子:

#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'; 
} 

输出:

1 
0 
0 
0 

注意:这是由Mooing Duck创建,且编译,更健壮的示例可以是发现于http://ideone.com/awrmK

+11

现在你已经回答“可以完成吗?”,“应该完成吗?”留给读者作为练习。 – msw

3

为什么你需要一个操作员?

inline bool RangeCheck(int a, int b, int c) 
{ 
    return a < b && b < c; 
} 

或:

#define RANGE_CHECK(a, b, c) (((a) < (b)) && ((b) < (c))) 
+1

该函数不适用于更复杂的比较,如'a < b > c> d 2012-06-13 23:04:54

+0

我想upvote这个,但后来我看到了预处理器滥用(在本世纪大多数使用'#define'被认为是有害的) – msw

+0

@msw这就是为什么我先把内联函数:) – kol