Overloaded C ++ operator with reverse associativity

It was very difficult to come up with a name ... (I am not a native speaker of English.)

struct A { int value; A operator+(int i) const { A a; a.value=value+i; return a; }; }; int main(){ A a; a.value=2; a=a+2; return 0; } 

This code compiles / works as expected, but when I change a = a + 2 to a = 2 + a, it will no longer compile. GCC gives me this error:

 no match for "operator+" in "2 + a" 

Is there a way to somehow make 2 + work like +2?

+4
source share
2 answers

You need a free function defined after class

 struct A { // ... }; A operator+(int i, const A& a) { return a+i; // assuming commutativity }; 

you might consider defining A& operator+=(int i); in A implement both versions of operator+ as free features. You may also be interested in Boost.Operators or other helpers to simplify A , see My Profile for two options.

+5
source

Of course, we define the inverse operator outside the class:

 struct A { int value; A operator+(int i) const { A a; a.value=value+i; return a; }; }; //marked inline to prevent a multiple definition inline A operator+(int i, const A& a) { return a + i; } 
+3
source

All Articles