views:

256

answers:

3

In my classes I often write a quick operator!= by returning !(*this == rhs), e.g.:

class Foo
{
private:
    int n_;
    std::string str_;
public:
    ...
    bool operator==(const Foo& rhs) const
    {
        return n_ == rhs.n_ && str_ == rhs.str_;
    }

    bool operator!=(const Foo& rhs) const
    {
        return !(*this == rhs);
    }
};

I can't see any obvious problems with doing this but thought I'd ask if anyone knows of any.

A: 

No, that's absolutely fine - I do exactly the same.

Mark Ingram
+11  A: 

I believe that's the preferred method of implementing operator!= so that you don't repeat yourself, and you have a guaranteed correct relationship with operator==.

bdukes
+2  A: 

Defining operator!= as !operator== is just fine

For getting these trivial equivalent operators easily defined, I always use Boost.Operators.
The case with only operator== and operator!= (i.e. using equality_comparable<>) doesn't gain very much.

But when you need less and greater than too, or some combination of operator+, operator* etc. this becomes very convenient.

An example for your case would read

class Foo : private boost::equality_comparable< Foo >
{
   private:
     int n_;
     std::string str_;
   public:
     ...
   bool operator==(const Foo& rhs) const
   {
      return n_ == rhs.n_ && str_ == rhs.str_;
   }

};
Pieter