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.
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==
.
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_;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With