Re: why not implicit operator !=()?
On 2012-03-15 08:07, Michael wrote:
This has probably been asked before but...
Is there a particular reason why when you define an operator ==()
for a type:
struct SomeType
{
bool operator== (const SomeType& rhs) const { return ...; }
};
... that the compiler doesn't also go ahead and implicitly define
operator !=() for you?
Please no! First, this would silently change the semantics of existing
programs. Implicit member declarations are hard to explain, and during
the C++11 standardization one of the previous implicit member
declarations has now been deprecated: If a class type has a
user-declared copy-assignment operator [copy constructor] or destructor,
the implicit copy constructor [copy-assignment operator] declaration is
now deprecated.
This omission has become a pet peeve of mine lately...
I understand that and I would be much in favour for extending the
concept of defaulted member functions. I would very much like your
example if you had suggested
struct SomeType
{
bool operator==(const SomeType& rhs) const { return ...; }
bool operator!=(const SomeType& rhs) const = default;
};
for example. Extending the possibility of defaulted functions was an
early idea during the C++11 standardization process, see e.g.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2584.html
and the ==/!= example has already been mentioned in
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2210.html
But they were simply too late for C++11. IMO extending defaulted
functions to
==
!=
<
<=
=
swap
would be a great idea. But it is important to get the semantics right: I
expect that if I write
struct SomeType
{
bool operator==(const SomeType& rhs) const { return ...; }
bool operator!=(const SomeType& rhs) const = default;
} s1, s2;
the semantics of s1 != s2 is exactly that of !(s1 == s2), but what if
you write
struct SomeType
{
bool operator!=(const SomeType& rhs) const = default;
} s1, s2;
? Does this define member-wise inequality? Another more severe problem
to solve would be a mixture of free and member functions. Consider:
struct SomeType
{
int a, b;
bool operator!=(const SomeType& rhs) const = default;
// return (a == rhs.a) && (b == rhs.b) ??
} s1, s2;
bool operator==(const SomeType& lhs, const SomeType& rhs) { return lhs.a
== rhs.a; }
// User says: SomeType::b is no member contributing to ==
Unfortunately these examples reveal some serious problems to solve.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]