有没有办法提取多个相似函数的外循环?

Jam*_*esM 6 c++ code-duplication

示例:我想从这些运算符函数中提取嵌套的 for 循环,这些运算符函数除了一行之外都是相同的。

// 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;
}
Run Code Online (Sandbox Code Playgroud)

cig*_*ien 10

您可以编写一个接受二元函数并将其应用于循环内所有元素对的函数模板

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)); 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它

// 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;
}
Run Code Online (Sandbox Code Playgroud)