Boost logo

Boost :

From: Daniel Frey (d.frey_at_[hidden])
Date: 2000-11-24 06:11:38


Hi,

I just wrote a little helper class that allows to define operator< for
my own classes in a special way so that I can write

if( a < b < c ) ...

Of course it can't work with build-in types and that's why I'm not
sure if this helper class should better be locked away and someone
should lose the key or if it could be helpful to increase readability.
In the latter case, it could be added to Boost - if you like. Before I
talk to much, the helper class and a small example:

--- code ---

#include <iostream>
using namespace std;

template< typename T > class comp_result
{
private:
   const bool result_;
   const T& value_;
   
public:
   comp_result( const T& value )
      : result_( true ), value_( value ) {}
   comp_result( const bool result, const T& value )
      : result_( result ), value_( value ) {}
   ~comp_result() {}
   
   operator bool() const { return result_; }
   const T& value() const { return value_; }
};

class A
{
private:
   int i_;

public:
   A( int i ) : i_( i ) {}
   ~A() {}
   
   friend comp_result<A> operator<( const comp_result<A>& lhs,
                                    const A& rhs )
   {
      return comp_result<A>( lhs && lhs.value().i_ < rhs.i_, rhs );
   }
   
   friend comp_result<A> operator>( const comp_result<A>& lhs,
                                    const A& rhs )
   {
      return comp_result<A>( lhs && lhs.value().i_ > rhs.i_, rhs );
   }
};

int main()
{
   A a = 1;
   A b = 2;
   A c = 3;

   if( a < b < c ) cout << "y";
   if( b < a < c ) cout << "n";
   
   if( !(a < c < b) ) cout << "y";
   
   if( c > b > a ) cout << "y";
   if( c < a < b ) cout << "n";

   if( b < c > a ) cout << "y"; // Doh!

   cout << " <- should equal 'yyyy'" << endl;
   
   return 0;
}

--- end code ---

I am aware that this might cause a lot of problems, including
overhead, newbie's transfering this pattern to build-in types,
boost/operators.hpp may not be usable with it, etc. - this is why I
want some feedback. Any comments on this are welcome...

Regards, Daniel


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