I created a matrix class:
template <typename T>
class Matrix
{
public:
Matrix(size_t n_rows, size_t n_cols);
Matrix(size_t n_rows, size_t n_cols, const T& value);
void fill(const T& value);
size_t n_rows() const;
size_t n_cols() const;
void print(std::ostream& out) const;
T& operator()(size_t row_index, size_t col_index);
T operator()(size_t row_index, size_t col_index) const;
bool operator==(const Matrix<T>& matrix) const;
bool operator!=(const Matrix<T>& matrix) const;
Matrix<T>& operator+=(const Matrix<T>& matrix);
Matrix<T>& operator-=(const Matrix<T>& matrix);
Matrix<T> operator+(const Matrix<T>& matrix) const;
Matrix<T> operator-(const Matrix<T>& matrix) const;
Matrix<T>& operator*=(const T& value);
Matrix<T>& operator*=(const Matrix<T>& matrix);
Matrix<T> operator*(const Matrix<T>& matrix) const;
private:
size_t rows;
size_t cols;
std::vector<T> data;
};
Now I want to enable operations between matrix of different types, for example:
Matrix<int> matrix_i(3,3,1); // 3x3 matrix filled with 1
Matrix<double> matrix_d(3,3,1.1); // 3x3 matrix filled with 1.1
std::cout << matrix_i * matrix_d << std::endl;
I thought to do like this (is the right way?):
template<typename T> // Type of the class instantiation
template<typename S>
Matrix<T> operator*(const Matrix<S>& matrix)
{
// Code
}
I think this will work fine if I multiply a double matrix with an integer matrix: I will obtain a new double matrix. The problem is that if I multiply an integer matrix with a double matrix I will lose some information, because the matrix I obtain will be an integer matrix… Right? How can I fix this behave?
std::cout << matrix_d * matrix_i << std::endl; // Works: I obtain a 3x3 matrix full of 1.1
std::cout << matrix_i * matrix_d << std::endl; // Doesn't work: I obtain a 3x3 matrix full of 1 instead of 1.1
To do what you want, you will need to offer an
operator*that returns aMatrix<X>whereXis the type with the largest range/greatest precision.If you have a C++11 compiler at hand, you could use:
Assuming that you have
operator*=implemented as a template that allows multiplications with other instantiations ofMatrix<T>and that you have a conversion constructor.