Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick and dirty operator!=

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.

like image 484
Rob Avatar asked Jan 12 '09 19:01

Rob


2 Answers

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==.

like image 197
bdukes Avatar answered Nov 20 '22 22:11

bdukes


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

};
like image 26
Pieter Avatar answered Nov 20 '22 23:11

Pieter