Re: Bug, or huge inconsistency in C++ Standard?
* Carlos Moreno:
I just noticed that I can overload operator+= (and I didn't try, but
I guess all other assignment operators except = ) as a non-member
function.
Is this a bug in g++ 4.0
Yes.
or does the standard allow for this horrible
and huge inconsistency?
Depends what inconsistency "this" refers to.
+=, -=, etc., are all *assignment* operators; why if the overloaded
assignment operator must be a class member, the other assignment
operators aren't?
A user-defined assignment operator must be a non-static member function
with exactly one argument.
In fact, what I tried was:
int & operator+= (int &, const X & x);
Nice, isn't it? This allows me to overcome/circumvent the limitation
of not being allowed to overload-on-return-type for some cases ---
depending on the data type of the l-value on the left of the assignment,
the conversion from class X is handled properly.
I guess my question should be: what is the rationale for not being
allowed to do int & operator= (int &, const Class &) ??
The original rationale, as explained by Bjarne Stroustrup in TCPPPL, was
to preserve some degree of predictability by having some operations that
couldn't be redefined by programmers.
I'm not sure whether overloading of operators for enumerations was
introduced after that.
But anyway, the operators that cannot be overloaded by namespace scope
definitions (namely operator=, operator op=, operator(), operator[] and
operator->) are those that would be "suprising" for enumerations.
At a guess, a further rationale could be what you've already mentioned
about overloading on return type (I haven't seen that before), which is
much less natural for e.g. operator&&, although it could be pressed into
such service.
But the rationale question is better asked in [comp.std.c++].
Obviously, the corollary question is: is it rather a bug in my
compiler that it is allowing me to overload += in that way?
Yes.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]