I’m writing a matrix class and I want to be able to cast a fixed sized matrix to an fixed sized double array. Although, I have troubles implementing the appropriate cast operator. What I’ve implemented so far does not work:
template<unsigned int M, unsigned int N>
class Matrix
{
typedef double (&ArrayType)[M][N];
public:
operator ArrayType();
}
Matrix<3,3> mat1;
double matArr[3][3];
matArr = mat1;
error: incompatible types in assignment of ‘sfz::Matrix<3u, 3u>’ to
‘double [3][3]’
Casting the matrix explicitly causes another error:
error: ISO C++ forbids casting to an array type ‘double [3][3]’
Is there no way to implement the syntax i want to achieve?
You can’t assign arrays, ever. Live with it.
To make your function work, you could make a reference:
Alternatively, you could wrap your naked array in something like
std::array<std::array<double, M>, N>and return that by value. That’s why wrappers likestd::arrayexist – they allow you to treat arrays like values. The same trick has worked in C since day one (putting an array inside a struct), but it’s actually nice and readable in C++: