-
Template arguments
I am implementing a class for matrices (the mathematical object), and I am unsure how the definition for the multiplication operator should look. My class is defined as:
Code:
template <class T, int rows, int columns> class matrix {
// Members, operators, etc.
};
The following code should well illustrate what I would like to do, even though it cannot compile:
Code:
template <class T, int rows, int columns> class matrix {
// Members, operators, etc.
matrix<T, rows, cols> operator*(const matrix<T, columns, int cols> &m);
}
As you might recall from the linear algebra, the product of two matrices has dimensions as follows: [m x n][n x p] = [m x p]. Note the dimensions of the (thought) returned matrix above. If you know linear algebra, you will understand the problem ;)
-
First, you use "columns" in the first line, but "cols" in the return value of your second function.
Second, you probably want to be able to allocate different size matracies durring runtime. This means you will want your rows and colums to be constructor peramitters, not template arguements.
-
cols is not the same as columns, and should not be.
I have a matrix A of type [m x n]. In that matrix, I want to have an operator* which will take a matrix B of type [n x p] as an argument, and returns a matrix AB of type [m x p]. So, the problem is that the return type depends on the argument type.
And no, I do not want to have the matrix dimensions as constructor arguments, for many reasons. The strongest one is that I want the compiler to check if the sum/product/whatever is defined.
-
You can't do it that way. All template paramitters must be defined at compiletime.
You must then either pass cols as a seperate parammiter of matrix, or create an external function that takes cols as a function parmitter. In either case, the return type of the function must be known at compiletime, so if I understand what you're trying to do correctly, it won't work.
-
Code:
template <class Tm, int M, int N>
class Matrix{
...
template <int Mm, int Nm>
Matrix<Tm, M, Nm> operator *(Matrix<Tm, Mm, Nm>& m);
template <int Mm, int Nm>
Matrix<Tm, M, Nm> multiply(Matrix<Tm, Mm, Nm>& m);
...
};
USAGE:
Matrix<int, 3,1> m1;
Matrix<int, 1,3> m2;
Matrix<int, 3,3> m3 = m1.operator* <1,3>( m2 );
OR
Matrix<int, 3,3> m4 = m1.multiply <1,3>( m2 );
Granted, it's not very cute from a mathematical point of view, but it should work.
And it's the best way I can think of if you want templated Matrices... =/
Edit:
I haven't tried the code myself, but the following might also work.
Code:
Matrix<int, 3,3> m5 = m1 * m2;
-
I tink that was what I was looking for, thank you! It's too late to try it now, but tomorrow.. :)