C ++ operator overloads a template with different arguments

I am opening C ++ and I would like to create a librairy mini math matrix using templates.

Here I want to overload the * operator.

If I describe such a matrix: M(y, x) with M name of the matrix, y and x height and width, the matrix multiplication should look like this:

 M(a, b) * N(b, c) = R(a, c) 

I currently have this code:

 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; }; 

So, I would like to be able to multiply two different matrices:

 Matrix<3, 4> m; Matrix<4, 2> n; // fill the matrix with values Matrix<3, 2> o = m * n; 

I searched, but I did not find the answer to this question (perhaps because I really do not know what I should look for exactly).

Thank you for your help:)

+5
source share
2 answers

You need to create an operator* function of the template member, for example:

 template <unsigned int y2, unsigned int x2> Matrix<y, x2> operator*(const Matrix<y2, x2>& right) { // code... } 

Note that the return type is no longer a reference, since operator* must return a new value - if you want, you can define an additional operator*= that changes the LHS matrix in place.

Another thing to note is that matrix multiplication only makes sense if the sizes of the matrices are consistent: that is, if the number of columns in LHS matches the number of rows in RHS. To ensure this is done, you can use static_assert inside your member function to make sure the template parameters are consistent:

 template <unsigned int y2, unsigned int x2> Matrix<y, x2> operator*(const Matrix<y2, x2>& right) { static_assert(y2 == x, "Matrix dimensions mismatched"); // code... } 
+3
source

It's pretty simple, define operator* as a function template. An example of a free function template:

 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; } 

Note that operator* returns a value. this is especially important since you are returning a different type and have no object to return the link (idiomatic correctness to the side).

0
source

Source: https://habr.com/ru/post/1258720/


All Articles