Reputation: 535
I have this code which I need to make it be compiled:
int main () {
const Matrix<int, 3, 2> m1; // Creates 3*2 matrix, with all elements set to 0;
Matrix<int, 3, 3> m2(4); // Creates 3*3 matrix, with all elements equals to 4;
const Matrix<int, 3, 3> m3 = m2; // Copy constructor may take O(MN) and not O(1).
cout << m3 * m1 << endl; // You can choose the format of matrix printing;
I already implemented the operator<<
for the template matrix.
the problem is to implement operator*
such that creating a new matrix with the template params of m3.rows and m1.cols, i.e. right return type in the signature of operator*
result expression.
I tried:
Matrix<int, lhs.rows, rhs.cols> operator *(const MatrixBase& lhs, const MatrixBase& rhs)
Matrix<?> res; // not sure how to define it
{
for (int i = 0; i < lhs.get_columns(); i++)
{
for (int j = 0; j < rhs.get_rows(); j++)
{
for (int k = 0; k < lhs.get_columns(); k++)
{
res[i][j] = lhs[i][k] * rhs [k][j];
}
}
}
}
the class MatrixBase is just a non-template abstract class that Matrix is derived from, a try to make operator*
generic.
the problem is that lhs
and rhs
are not initialized yet and it does not compile, I thought of making the operator*
as a method of Matrix but I am still stuck on the return type.
I know that template is determined with the preprocessor but I'm sure that there is a way to make it run.
Upvotes: 0
Views: 65
Reputation: 12928
Your questions lacks some information about what MatrixBase
is, but if we just look at your Matrix
class you need a template function to do this. There you can deduce the template parameters of the classes and use that to calculate the resulting type.
template <typename T, int LRows, int LCols, int RRows, int RCols>
Matrix<T, LRows, RCols> operator*(const Matrix<T, LRows, LCols>& lhs, const Matrix<T, RRows, RCols>& rhs) {
static_assert(LCols == RRows, "Invalid matrix multiplication");
Matrix<T, LRows, RCols> result;
// ... do the calculations
return result;
}
Upvotes: 2