Compiler Friendly Matrices [download]
[view Matrix.h, Matrix.inline.h, Matrix.cpp]
depends on:
nothing
This is a c++ matrix class designed to minimize errors at runtime and allow the compiler to optimize as much as possible. The class uses three template arguments:
- The data type used (i.e. float or double)
- The matrix width (nb of columns)
- The matrix height (nb of columns)
template<class _T, int _WIDTH, int _HEIGHT>
class Matrix { ... };
|
I have seen several implementations of matrices in C++ where the size of the matrix is given as a parameter to the constructor and the storage is build dynamically. Here, having the width and height as template parameters has several advantages over the tradition dynamic matrix class:
- The compiler knows how many elements you have in your matrix and can unroll and optimize loops
- You can ensure that you are not doing operations on matrices with incompatible sizes (multiplcation for example). The compiler will tell you at compile time if you do.
- When you receive a matrix as a function parameter, you don't
need to check that it is what you expect it to be. For example,
if your function expects a 4x4 matrix, you'll ask for a
Matrix
and you are guaranteed to get what you asked for.
There are a few typedefs at the bottom for convenience:
typedef Matrix<float, 1, 1> Matrix1f; typedef Matrix<float, 2, 2> Matrix2f; typedef Matrix<float, 3, 3> Matrix3f; typedef Matrix<float, 4, 4> Matrix4f; typedef Matrix<double, 1, 1> Matrix1d; typedef Matrix<double, 2, 2> Matrix2d; typedef Matrix<double, 3, 3> Matrix3d; typedef Matrix<double, 4, 4> Matrix4d; |
So you can use Matrix4d instead of
Matrix
For the rest, just have a look at the header file to see what's available. In short, you can do things like:
static double m[9] = {
1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0
};
Matrix3d m3d = Matrix3d(m);
m3d[0][1] = 0;
m3d += Matrix3d::identityMatrix();
m3d.transpose();
m3d = m3d * Matrix4d::identityMatrix(); // ERROR: the compiler will complain
|
[TextCounter Fatal Error: Could Not Write to File __petitg_cpp_matrix_html]

