Lud*_*ope 5 c++ templates arguments operator-keyword
我正在发现C++,我想使用模板创建一个迷你数学Matrix librairy.
在这里,我想重载运算符*.
如果我描述了这样的矩阵:M(y, x)以M矩阵的名称,y以及x高度和宽度,矩阵乘法看起来应该:
M(a, b) * N(b, c) = R(a, c)
Run Code Online (Sandbox Code Playgroud)
目前我有这个代码:
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;
};
Run Code Online (Sandbox Code Playgroud)
所以我希望能够将两个不同的矩阵相乘:
Matrix<3, 4> m;
Matrix<4, 2> n;
// fill the matrix with values
Matrix<3, 2> o = m * n;
Run Code Online (Sandbox Code Playgroud)
我搜索了但是我没有找到这个问题的答案(也许是因为我真的不知道我必须要搜索的内容).
谢谢你的帮助 :)
您需要创建operator*一个模板成员函数,如下所示:
template <unsigned int y2, unsigned int x2>
Matrix<y, x2> operator*(const Matrix<y2, x2>& right)
{
// code...
}
Run Code Online (Sandbox Code Playgroud)
请注意,返回类型不再是引用,因为operator*应该返回一个新值 - 如果您愿意,您可以定义一个补充值operator*=来就地修改 LHS 矩阵。
另一件需要注意的事情是,矩阵乘法仅在矩阵维度一致时才有意义:即,如果 LHS 中的列数与 RHS 中的行数匹配。为了强制执行此操作,您可以static_assert在成员函数中使用 a 来确保模板参数一致:
template <unsigned int y2, unsigned int x2>
Matrix<y, x2> operator*(const Matrix<y2, x2>& right)
{
static_assert(y2 == x, "Matrix dimensions mismatched");
// code...
}
Run Code Online (Sandbox Code Playgroud)