我在寫矩陣模板類。一切順利,直到我超載乘法運算符。我的階級是這樣的:C++矩陣模板,矩陣矩陣和矩陣數相乘之間的模糊
template <typename TNum> class Matrix
{
private:
// ...
TNum* Data;
public:
const TMatIdx NRows; // Type TMatIdx defined somewhere else.
const TMatIdx NCols;
const TMatIdx Size;
// ...
// Matrix * matrix
template <typename T2>
const Matrix<TNum> operator*(const Matrix<T2>& right) const;
// Matrix * number
template <typename T2>
Matrix<TNum>& operator*=(const T2& scale);
};
// Matrix * number
template <typename TNum, typename T2>
Matrix<TNum> operator*(Matrix<TNum> lhs, const T2& rhs);
// Number * matrix
template <typename TNum, typename T2>
Matrix<TNum> operator*(const T2& lhs, Matrix<TNum> rhs);
我希望能涵蓋矩陣和數字之間的所有可能的乘法組合具有相同*
運營商。
然後我寫了乘以2 Matrix<double>
秒的小測試程序,我鐺++編譯器抱怨歧義:
test.cpp:46: error: ambiguous overload for 'operator*' in 'M * N'
matrix.h:225: note: candidates are: const QCD::Matrix<TNum> QCD::Matrix<TNum>::operator*(const QCD::Matrix<T2>&) const [with T2 = double, TNum = double]
matrix.h:118: note: QCD::Matrix<TNum> QCD::operator*(const T2&, QCD::Matrix<TNum>) [with TNum = double, T2 = QCD::Matrix<double>]
matrix.h:109: note: QCD::Matrix<TNum> QCD::operator*(QCD::Matrix<TNum>, const T2&) [with TNum = double, T2 = QCD::Matrix<double>]
test.cpp:52: error: ambiguous overload for 'operator*' in 'M * N'
matrix.h:225: note: candidates are: const QCD::Matrix<TNum> QCD::Matrix<TNum>::operator*(const QCD::Matrix<T2>&) const [with T2 = double, TNum = double]
matrix.h:118: note: QCD::Matrix<TNum> QCD::operator*(const T2&, QCD::Matrix<TNum>) [with TNum = double, T2 = QCD::Matrix<double>]
matrix.h:109: note: QCD::Matrix<TNum> QCD::operator*(QCD::Matrix<TNum>, const T2&) [with TNum = double, T2 = QCD::Matrix<double>]
是否有可能克服這種模糊性,而不必明確寫下T2所有可能的特例?
,僅供參考,這裏是我的實現:
template<typename TNum> template <typename T2>
Matrix<TNum>& Matrix<TNum> ::
operator*=(const T2& rhs)
{
for(TMatIdx i = 0; i < Size; i++)
Data[i] *= rhs;
return *this;
}
template<typename TNum> template <typename T2>
const Matrix<TNum> Matrix<TNum> ::
operator*(const Matrix<T2>& right) const
{
Matrix<TNum> c(NRows, right.NCols);
TNum sum_elems;
for(TMatIdx i = 0; i < NRows; i++)
{
for(TMatIdx j = 0; j < right.NCols; j++)
{
sum_elems = TNum(0);
for(TMatIdx k = 0; k < right.NRows; k++)
{
sum_elems += at(i, k) * right.at(k, j);
}
c.at(i, j) = sum_elems;
}
}
return c;
}
template <typename TNum, typename T2>
Matrix<TNum> operator*(Matrix<TNum> lhs, const T2& rhs)
{
lhs *= rhs;
return lhs;
}
template <typename TNum, typename T2>
Matrix<TNum> operator*(const T2& lhs, Matrix<TNum> rhs)
{
rhs *= lhs;
return rhs;
}
向我們展示乘法。 – 0x499602D2