带有不同参数的c++操作符重载模板
C++ operator overload template with different arguments
我正在学习c++,我想用模板创建一个迷你的数学矩阵库。
这里,我想重载操作符*.
如果我这样描述一个矩阵:M(y, x)
, M
是矩阵名,y
和x
是高度和宽度,矩阵乘法应该是这样的:
M(a, b) * N(b, c) = R(a, c)
目前我有这个代码:
template<unsigned int y, unsigned int x>
class Matrix
{
public:
Matrix() { }
~Matrix() { }
Matrix<y, x2>& operator*(const Matrix<y2, x2>& right)
{
// code...
}
private:
std::array<std::array<double, x>, y> m_values;
};
所以我希望能够像这样将两个不同的矩阵相乘
Matrix<3, 4> m;
Matrix<4, 2> n;
// fill the matrix with values
Matrix<3, 2> o = m * n;
我已经搜索了,但是我没有找到这个问题的答案(也许是因为我真的不知道我必须搜索什么)。
谢谢你的帮助
您需要将operator*
设置为模板成员函数,如下所示:
template <unsigned int y2, unsigned int x2>
Matrix<y, x2> operator*(const Matrix<y2, x2>& right)
{
// code...
}
注意,返回类型不再是一个引用,因为operator*
应该返回一个新值——如果您愿意,您可以定义一个补充的operator*=
,它可以就地修改LHS矩阵。
另一件需要注意的事情是,只有当矩阵的维数一致时,矩阵乘法才有意义:也就是说,如果LHS中的列数与RHS中的行数匹配。为了加强这一点,可以在成员函数中使用static_assert
来确保模板参数一致:
template <unsigned int y2, unsigned int x2>
Matrix<y, x2> operator*(const Matrix<y2, x2>& right)
{
static_assert(y2 == x, "Matrix dimensions mismatched");
// code...
}
这很简单,将operator*
定义为函数模板。自由函数模板示例:
template<unsigned y1, unsigned x1, unsigned y2, unsigned x2>
Matrix<y1, x2> operator*(Matrix<y1, x1> const& l, Matrix<y2, x2> const& r)
{
// static_assert(x1 == y2, "Matrices cannot be multiplied");
Matrix<y1, x2> ret{};
// multiply
return ret;
}
请注意,operator*
按值返回。这一点尤其重要,因为您返回的是不同的类型,并且没有对象可以返回引用(不考虑习惯用法的正确性)。