Boost logo

Boost Users :

Subject: [Boost-users] Idea: Chained comparison
From: Michiel Helvensteijn (m.helvensteijn_at_[hidden])
Date: 2008-11-17 15:43:05


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

-- 
Michiel Helvensteijn

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