mercredi 18 septembre 2019

How to initialize a 2D C-style array from a nested std::initializer_list?

I am creating a Matrix<type, width, height> class which I want to be able to initialize using initializer_list, for instance:

Matrix<int, 2, 2> mat = Matrix<int, 2, 2>{ {1,2},{3,4} };

The matrix is implemented using a T[height][width] 2D array.

To do this, I have tried making a constructor such as:

Matrix(std::initializer_list< std::initializer_list<T>> input);

However, I do not know how to fill the array with from the list. I have tried

  • using memcpy (corrupted memory),

  • std::copy (seems it is not possible to copy from an std::initializer_list),

  • as well as used the assignment operator and () constructor call (but 2D arrays are not assignable and () constructor call does not compile).

Is there any other way, preferably as safe as possible, to do this?

Aucun commentaire:

Enregistrer un commentaire