我在写矩阵模板类。一切顺利,直到我超载乘法运算符。我的阶级是这样的: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