![](/img/trans.png)
[英]C++ Matrix template, ambiguity between matrix-matrix and matrix-number multiplication
[英]Template Matrix-Matrix multiplication c++
我正在嘗試使用模板做矩陣-矩陣乘法,並且不斷出現以下錯誤。 (我試圖乘以非平方矩陣)
錯誤1錯誤C2593:“運算符*”不明確
有人可以給我建議如何解決此問題嗎?
//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();
}
矩陣乘法可能會由於模板中的編碼錯誤而出現問題。
錯誤在這里:
./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.
更改為此:
friend Matrix<T, m, l> operator*(const Matrix<T, m, n>&, const Matrix<T, n, l>&);
我必須更改Richard更改的內容,但還必須更改operator*
和friend
的聲明,如下所示:
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
和:
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>&);
如果我沒有更改這兩個中的第一個,則會出現“ operator*
is aambiguous”錯誤,因為前向聲明與進一步向下的實例化不匹配。
當前正在輸出:
0
1
2
這似乎不太正確,但是我還不夠清醒,無法進一步調試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.