I am trying to do Matrix-Matrix multiplication with template and I keep getting following error. ( I am trying to multiply non-square matrix)
Error 1 error C2593: 'operator *' is ambiguous
Can any one give me an advice on how to fix this?
//Matrix.h
#pragma once
#include <iostream>
#include <vector>
using namespace std;
template<class T, int m, int n>
class Matrix;
template<class T, int m, int n, int l>
Matrix<T, m, n> operator*(const Matrix<T, m, n>&, const Matrix<T, n, l>&);
template<class T, int m, int n>
class Matrix
{
vector<vector<T>> elements;
int nrow;
int ncol;
public:
Matrix();
~Matrix();
void print();
template<int l>
friend Matrix<T, m, l> operator*<>(const Matrix<T, m, n>&, const Matrix<T, n, l>&);
};
template<class T, int m, int n>
Matrix<T, m, n>::Matrix() : nrow(m), ncol(n)
{
for (int i = 0; i < nrow; i++){
vector<T> row(ncol, i);
elements.push_back(row);
}
}
template<class T, int m, int n>
Matrix<T, m, n>::~Matrix(){}
template<class T, int m, int n>
void Matrix<T, m, n>::print()
{
for (int i = 0; i < nrow; i++){
for (int j = 0; j < ncol; j++){
cout << elements[i][j] << " ";
}
cout << endl;
}
}
template<class T, int m, int n, int l>
Matrix<T, m, l> operator*(const Matrix<T, m, n>& m1, const Matrix<T, n, l>& m2){
int nrow = m1.nrow;
int ncol = m2.ncol;
Matrix<T, m, l> m3;
for (int i = 0; i < nrow; ++i){
for (int j = 0; j < ncol; ++j){
m3.elements[i][j] = 0;
for (int k = 0; k < m1.ncol; k++){
T temp = m1.elements[i][k] * m2.elements[k][j];
m3.elements[i][j] = temp + m3.elements[i][j];
}
}
}
return m3;
}
//main.cpp
#include "Matrix.h"
using namespace std;
int main()
{
Matrix<int, 3, 2> a;
Matrix<int, 2, 1> b;
Matrix<int, 3, 1> c;
c = a*b;
c.print();
}
The problem occurs in the matrix multiplication possibly due to the coding error in the template.
The error is here:
./matrix.cpp:48:28: error: function template partial specialization is not allowed
friend Matrix<T, m, l> operator*<>(const Matrix<T, m, n>&, const Matrix<T, n, l>&);
^ ~~
1 error generated.
change it to this:
friend Matrix<T, m, l> operator*(const Matrix<T, m, n>&, const Matrix<T, n, l>&);
I had to change what Richard changed, but I also had to change the declaration of operator*
and the friend
as follows:
template<class T, int m, int n, int l>
Matrix<T, m, l> operator*(const Matrix<T, m, n>&, const Matrix<T, n, l>&);
// ^ here
and:
template<class _T, int _m, int _n, int l>
friend Matrix<_T, _m, l> operator*(const Matrix<_T, _m, _n>&, const Matrix<_T, _n, l>&);
I got the " operator*
is ambiguous" error if I didn't change the first of these two, since the forward declaration doesn't match the instantiation further down.
It's currently outputting:
0
1
2
That doesn't seem quite right, but I'm not awake enough to debug further.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.