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 create operator*
such that create a new matrix with the template params of m3.rows and m1.cols, the problem it's to define the return type in the signature of operator*
.
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 are derivedfrom, 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 still stuck on the return type.
I know that template determined with the preprocessor but I'm sure that there is a way to make it run.
question from:
https://stackoverflow.com/questions/65860052/how-to-make-template-function-operator-deduce-template-arguments-implicitly 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…