ok so im not sure if its related to functors but from what i understood it is so the question is: lets assume i have the next class:
class Matrix{
public:
Matrix(int, int); // constructor
Matrix(const Matrix&); // copy constructor
Matrix& operator+= (const Matrix&);
Matrix& operator-= (const Matrix&);
int* operator[] (int) const;
private:
int rows;
int cols;
int** Mat_p;
};
and i want to overload the += and -= operators in Matrix class.
now, in order to sum or subtract 2 matrices we need to iterate over each value of both matrices and add or subtract so it will be some thing like:
Matrix& Matrix::operator+= (const Matrix& M){
for (int indexR = 0; indexR < rows; ++indexR)
for (int indexC = 0; indexC < cols; ++indexC)
Mat_p[indexR][indexC] += M[indexR][indexC];
}
Matrix& Matrix::operator-= (const Matrix& M){
for (int indexR = 0; indexR < rows; ++indexR)
for (int indexC = 0; indexC < cols; ++indexC)
Mat_p[indexR][indexC] -= M[indexR][indexC];
}
as you can see both operators "+=" and "-=" has the same structure give or take, so one of the basic so called "rules" is to avoid code duplication.
so the asked question is how do we avoid this duplication and keep the code effective ?
You could implement a single templated function and make two calls into it.
template<typename T>
Matrix& add_or_sub (const Matrix& M, const T &op){
for (int indexR = 0; indexR < rows; ++indexR)
for (int indexC = 0; indexC < cols; ++indexC)
Mat_p[indexR][indexC] = op(Mat_p[indexR][indexC], M[indexR][indexC]);
return *this;
}
Matrix& Matrix::operator+= (const Matrix& M){
return add_or_sub(M, std::plus());
}
Matrix& Matrix::operator-= (const Matrix& M){
return add_or_sub(M, std::minus());
}