skiddybag
skiddybag

Reputation: 1

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

I am writing a Matrix class that must support multiple operations. One of them is to multiply a matrix by either another matrix, or a scalar of the same type of the matrix data. Another is to implement the *= operator.

Current code (working):

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;
}

My question: is it possible to implement the *= operator such that there does not need to be 2 different functions? I am also curious if something similar can be done with the * operator as well, given that the code in those methods is very different due to the nature of matrix multiplication so things are a little more elegant.

Upvotes: 0

Views: 223

Answers (1)

Stephen
Stephen

Reputation: 31

Functions should do one thing and do it well. If you find that you have two very different implementations in the same function, chances are your code would be more maintainable and easier to read if you split the function.

The split you have here is a good one. It is immediately clear that operator* has two main cases to contend with. One where you multiply by a scalar and another where you multiply by a matrix.

Upvotes: 3

Related Questions