order in which operator+ return

is there a way such that i could set the order is which operator+ can return? for example,
1
2
3
4
if (a>=b)
return operator+(a,b)
else
return operator+(b,a)

rather then in setting it in operator+
1
2
3
4
5
6
7
8
9
ClassName operator+(const ClassName& a, const ClassName& b)
{
if (a>=b)
// add c[i] = a[i] + b[i] from i = 0 to i = b-1
//and then add c[i] = a[i] from i = b to i = a
else 
// add c[i] = b[i] + a[i] from i = 0 to i = a-1
//and then add c[i] = a[i] from i = a to i = b
}

since i want the code in operator+ to be cut in half rather then doing one for a>=b and then the other
Any method will require you to check which one is biggest, regardless of how you recode it, unless you simply split the sum:
1
2
3
4
5
6
for (int i = 0; i < a.size(); ++i) {
   c[i] += a[i];
}
for (int i = 0; i < b.size(); ++i) {
  c[i] += b[i];
}

You'd still have to make sure c has a size of (at least) max(a.size(), b.size()) though.
Last edited on
You can make a function that will return the sum (like int Add(/*...*/)) that will return the sum of two terms (no need to check for the other conditions) and simply call that function in deceleration of operator+
That function would still need to know which array is largest, else it will go out of bounds when it tries to access a[i] and b[i] for values of i > min(a.size(), b.size())...
Oh! Sorry, misread the problem's code!
Topic archived. No new replies allowed.