Boost logo

Boost Users :

Subject: Re: [Boost-users] Idea: Chained comparison
From: Bruno Martínez Aguerre (br1_at_[hidden])
Date: 2008-12-31 13:06:10


I really like the idea. Python has this. I'm not sure it's possible to
implement it preserving short circuit evaluation. The implementation you
gave had this problem.

Bruno

On Mon, 17 Nov 2008 18:43:05 -0200, Michiel Helvensteijn
<m.helvensteijn_at_[hidden]> wrote:

> I just came up with this handy class. I was wondering if it might have a
> place in Boost somewhere. Perhaps it already exists, and I didn't find
> it?
>
> It creates a syntax for chained comparison expressions. Ideally you'd
> want
> to be able to do the following in C++:
>
> if (0 <= i < N <= INT_MAX) f();
>
> But this doesn't work as expected, because it would actually be evaluated
> like this:
>
> if (((0 <= i) < N) <= INT_MAX) f();
>
> You would actually need to use the following code:
>
> if (0 <= i && i < N && N <= INT_MAX) f();
>
> The alternative I propose is this:
>
> if (c(0) <= i < N <= INT_MAX) f();
>
> It has the advantage of being shorter, of being closer to the usual
> mathematical notation, and of evaluating i and N only once. This is
> useful
> if they have side-effects.
>
> It requires the following class and function (which I'm sure could be
> improved). What do you think?
>
> ---------------------------------------------------------------------
> template <class T>
> class Comparison {
> public:
> Comparison(T value, bool truth = true) :
> _last(value), _truth(truth) {}
> template<class U>
> Comparison<U> operator==(U val) {
> return Comparison<U>(val, _truth && _last == val);
> }
> template<class U>
> Comparison<U> operator!=(U val) {
> return Comparison<U>(val, _truth && _last != val);
> }
> template<class U>
> Comparison<U> operator<(U val) {
> return Comparison<U>(val, _truth && _last < val);
> }
> template<class U>
> Comparison<U> operator>(U val) {
> return Comparison<U>(val, _truth && _last > val);
> }
> template<class U>
> Comparison<U> operator<=(U val) {
> return Comparison<U>(val, _truth && _last <= val);
> }
> template<class U>
> Comparison<U> operator>=(U val) {
> return Comparison<U>(val, _truth && _last >= val);
> }
> operator bool() {
> return _truth;
> }
> private:
> T _last;
> bool _truth;
> };
>
> template <class T>
> Comparison<T> c(T val) {
> return Comparison<T>(val);
> }
> ---------------------------------------------------------------------
>


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net