Boost logo

Boost :

From: Aleksey Gurtovoy (agurtovoy_at_[hidden])
Date: 2002-03-22 00:23:47


Here's a version of 'operators<>' template that allows "lazy" instantiation
of complementing operators:

template< typename T >
struct operators
{
 private:
    T& self() { return static_cast<T&>(*this); }
    T const& self() const { return static_cast<T const&>(*this); }

 protected:
    bool operator>(T const& other) const { return (other < self()); }
    bool operator<=(T const& other) const { return !(other < self()); }
    bool operator>=(T const& other) const { return !(self() < other); }
    bool operator!=(T const& other) const { return !(self() == other); }

    T operator++(int) { T result(self()); ++self(); return result; }
    T operator--(int) { T result(self()); --self(); return result; }

    T operator*(T const& other) { return T(self()) *= other; }
    T operator+(T const& other) { return T(self()) += other; }
    T operator-(T const& other) { return T(self()) -= other; }
    T operator/(T const& other) { return T(self()) /= other; }
    T operator%(T const& other) { return T(self()) %= other; }
    T operator^(T const& other) { return T(self()) ^= other; }
    T operator&(T const& other) { return T(self()) &= other; }
    T operator|(T const& other) { return T(self()) |= other; }
    T operator<<(T const& other) { return T(self()) <<= other; }
    T operator>>(T const& other) { return T(self()) >>= other; }
};

template< typename T >
class my
    : public operators< my<T> > // note public inheritance
{
    typedef operators< my<T> > ops;

 public:
    using ops::operator++;
    using ops::operator>;
    using ops::operator<=;
    using ops::operator>=;

    my& operator++();
    friend bool operator<(my const&, my const&);
};

int main()
{
    my<int> m1;
    my<int> m2;

    ++m1;
    m2++;
    
    m1 > m2;
    m1 <= m2;

    // m1 != m2; // error
    // m1 << m2; // error

    return 0;
}

What do you think?

Aleksey


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk