簡體   English   中英

是否可以使C ++函數接受多種數據類型?

[英]Is it possible to make a C++ function that accepts multiple data types?

我正在編寫一個必須支持多種操作的Matrix類。 其中之一是將一個矩陣乘以另一個矩陣或相同類型矩陣數據的標量。 另一個是實現* =運算符。

當前代碼(有效):

template <typename T>
Matrix<T>& Matrix<T>::operator*=(const Matrix<T> &rhs) {
    Matrix<T> lhs = *this;
    *this = lhs*rhs;
    return *this;
}

template <typename T>
Matrix<T>& Matrix<T>::operator*=(T num) {
    Matrix<T> lhs = *this;
    *this = lhs * num;
    return *this;
}
template<typename T>
const Matrix<T> Matrix<T>::operator*(T scalar) const {
    Matrix<T> result(rows, cols);
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            //std::cout << "adding elements at [" << i << "][" << j << "]" << std::endl;
            result[i][j] = this->data[i][j] * scalar;
        }
    }
    return result;
}

template<typename T>
const Matrix<T> Matrix<T>::operator*(const Matrix<T> &b) const {
    Matrix<T> a = *this;
    if(a.cols != b.rows)
        throw DimensionMismatchException();
    int rows = a.rows;
    int cols = b.cols;
    Matrix<T> result(rows, cols);
    for(int i = 0; i < rows; i++)
    for (int j = 0; j < cols; j++)
        for(int k = 0; k < a.cols; k++)
            result[i][j] += a[i][k]*b[k][j];
    return result;
}

我的問題:是否可以實現* =運算符,從而不需要兩個不同的函數? 我也很好奇,是否也可以使用*運算符來完成類似的操作,因為由於矩陣乘法的性質,這些方法中的代碼有很大不同,因此事情會更加優雅。

函數應該做一件事並且做好。 如果發現同一功能中有兩個非常不同的實現,則拆分該功能時,您的代碼可能會更易於維護且更易於閱讀。

您在這里進行的拆分是個不錯的選擇。 顯然,運算符*有兩種主要情況要解決。 一個乘以標量,另一乘以矩陣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM