I'm building a class that has a slightly asymmetric addition. Before the complaints come in, it's necessarily asymmetric. There is a conversion (operation that takes a bit of time) that has to happen when two objects are added together, and the conversion most naturally happens with respect to the right summand.
To make this concrete, here's a generic example of what's going on...
class Foo {
char _fav;
int _prop;
public:
const char fav() const {return _fav;}
const int prop() const (return _prop;}
void changeFav(char); // complicated method that also changes _prop
void changeProp(int); // straightforward method
}
Foo
operator + (Foo A, Foo B) {
Foo sum;
if (A.fav() != B.fav()) A.changeFav(B.fav);
sum.changeProp(A.prop() + B.prop());
return sum;
}
In order for two Foo
s to be added, they need to have the same _fav
, so a choice must be made as to which to convert. Based on the details of Foo
, it's most natural to change the left summand to match the right summand.
However, when doing:
Foo A,B,C;
Foo D = A + B + C; // D = (A + B) + C
Foo E = A + (B + C);
if A
already has the same _fav
as C
, then changeFav
is called twice for D
(once to change A._fav
to B._fav
and then again to change (A+B)._fav
to C._fav
) and once for E
(to change B._fav
to C._fav
). I prefer the latter but want to avoid forcing the user to use parentheses for multiple additions.
Is there a way to overload the associativity of operator +
to make this happen?