Search code examples
c++code-duplication

Is there a way to extract outer loops of multiple similar functions?


Example: I want to extract the nested for loops from these operator functions that are the same except the one line.

// Add two matrices
Matrix& operator+=(const Matrix& other)
{
    for (int i = 0; i < this->m_rows; i++)
    {
        for (int j = 0; j < this->m_cols; j++)
        {
            (*this)(i, j) = (*this)(i, j) + other(i, j); // Only difference
        }
    }
    return *this;
}

// Subtract two matrices
Matrix& operator-=(const Matrix& other)
{   
    for (int i = 0; i < this->m_rows; i++)
    {
        for (int j = 0; j < this->m_cols; j++)
        {
            (*this)(i, j) = (*this)(i, j) - other(i, j); // Only different
        }
    }
    return *this;
}

Solution

  • You can write a function template that accepts a binary function and applies it on all pairs of elements inside the loops

    template<typename Op>
    void loops(const Matrix& other, Op op)
    {
        for (int i = 0; i < this->m_rows; i++)
        {
            for (int j = 0; j < this->m_cols; j++)
            {
                (*this)(i, j) = op((*this)(i, j), other(i, j)); 
            }
        }
    }
    

    and then use it like this

    // Add two matrices
    Matrix& operator+=(const Matrix& other)
    {
        loops(other, std::plus{});
        return *this;
    }
    
    // Subtract two matrices
    Matrix& operator-=(const Matrix& other)
    {   
        loops(other, std::minus{});
        return *this;
    }