In C++ (and C++11), classes defining a +
and +=
operators often define a -
and -=
operators that do nearly the same thing (except +
is replaced with -
in the function).
What is the best way to avoid duplicated code here (and still achieve good performance)? I am sure there is a good way to do it with functors:
Here's what I've tried:
#include <iostream>
#include <functional>
struct num {
int val;
const num & operator +=(const num & rhs) {
return op_equals<std::plus<int> >(rhs);
}
const num & operator -=(const num & rhs) {
return op_equals<std::minus<int> >(rhs);
}
template <typename op>
const num & op_equals(const num & rhs) {
op operation;
val = operation(val, rhs.val);
return *this;
}
};
int main() {
num x{1};
num y{2};
x += y;
std::cout << x.val << std::endl;
return 0;
}
Note that this is a simple example; in reality the code in the +=
and -=
operators is more complex.
Also, I am not married to functors in the solution-- any suggestions or advice?
operator+
in terms ofoperator+=
, which minimises repeated code. – Oli Charlesworth Jun 27 '12 at 21:53