[C++] Operator overloading

From: Pocaterra (olivertwist_at_dickens.co.uk)
Date: 10/27/04


Date: Tue, 26 Oct 2004 17:22:43 -0600

Hi:

I'm wondering if the following code sample is:

1. Legal (i.e., is using binary_function with reference template
arguments in the -= and += member operators okay)?
2. Efficient (i.e., will copy constructors or assignment operators be
called for class Foo)?
3. Too damn complicated for its own good (i.e., is their a better,
simpler approach, beyond just explicitly programming each operator)?!

Basically, I'm trying to use the template approach to minimize typing,
and minimize errors. On VC++ 7.0, it compiles, works, and doesn't
result in the copy constructors being called.

On a related note, I seem to recall having read that (for example) the -
operator should be implemented using the -= operator or,... vice versa.
  Is this true? If so, which way is correct: - using -=, or -= using -?
  And how is this done efficiently (again, so that copy constructors or
assignment operators are not called)? Is it any better than my approach?

Thanks,
Cameron

------

template<class Arg1, class Arg2, class Result>
class
minus_equals : public std::binary_function<Arg1, Arg2, Result>
{
public:
   result_type operator()(first_argument_type a, second_argument_type b )
     { return a -= b; }
};

template<class Arg1, class Arg2, class Result>
class
plus_equals : public std::binary_function<Arg1, Arg2, Result>
{
public:
   result_type operator()(first_argument_type a, second_argument_type b )
     { return a += b; }
};

class Foo
{
     int a;
     int b;

     template< typename Op >
     Observation binaryOp( const Foo& rhs, Op& op )
     {
         return Foo(
             op( a, rhs.a),
             op( b, rhs.b) );
     }

     Foo operator-( const Foo& rhs )
         { return binaryOp(rhs, std::minus<double>() ); }
     Foo operator+( const Foo& rhs )
         { return binaryOp(rhs, std::plus<double>() ); }

     Foo& operator-= ( const Foo& rhs )
     {
         binaryOp(rhs, minus_equals<double&, double, double&>() );
         return *this;
     }
     Foo& operator+= ( const Foo& rhs )
     {
         binaryOp(rhs, plus_equals<double&, double, double&>() );
         return *this;
     }
};

int main()
{
     Foo fa, fb;

     fb -= fa;

     // etc.
}


Quantcast