I’m writing a generic matrix class in c++. I want to be able to initialize a matrix from a two dimensional double array. Because I’m using templates and therefor matrix sizes need to be known at compile time, I want to make sure that just arrays of a given size can be passed to the constructor. Expressed in code this is:
template<unsigned int M, unsigned int N>
class Matrix {
public:
Matrix(double (&values)[M][N]);
}
Now, here comes the odd part: Like expected the following code works like a charm:
double arr [3][3] = { {1,2,3},
{1,2,3},
{1,2,3} };
Matrix<3,3>* mat3x3p = new Matrix<3,3>(arr);
But when passing the array anonymously the code is broken:
Matrix<3,3>* mat3x3p = new Matrix<3,3>({ {1,2,3},
{1,2,3},
{1,2,3} });
The same applies also to construction through assignment.
The exact error message is:
no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘double (&)[3][3]’
That would be binding a temporary to an (lvalue) reference to non-
const, and that’s not allowed. If you change to a reference toconstthen that would work — although in the case of an array it’s a bit weird as cv-qualifiers apply to the element type, not the array itself. Nonetheless, if you havethen
is valid in C++11, thanks to list initialization. I don’t know of a way to make it work for C++03.