I want to make it possible to pass brace-enclosed initializer list to my constructor of my class which represents a matrix of fixed dimension. This is the code what I have:
#include <cstddef>
#include <array>
template <typename T, size_t N, size_t M>
using array2d = std::array<std::array<T, N>, M>;
template <typename T, size_t N, size_t M>
class Matrix {
private:
array2d<T, N, M> value;
public:
Matrix(const array2d<T, N, M>& value) : value(value) {}
};
int main() {
Matrix<double, 2, 3> mat1 ({
{1, 2, 3},
{4, 5, 6}
});
}
My assumption was that array2d
is automatically created from initializer list that I'm passing as argument to constructor, but that doesn't seem to be the case, as the compiler throws the following error:
1704186652/source.cpp:16:23: error: no matching constructor for initialization of 'Matrix<double, 2, 3>'
Matrix<double, 2, 3> mat1 ({
^ ~
1704186652/source.cpp:8:7: note: candidate constructor (the implicit copy constructor) not viable: cannot convert initializer list argument to 'const Matrix<double, 2, 3>'
class Matrix {
^
1704186652/source.cpp:8:7: note: candidate constructor (the implicit move constructor) not viable: cannot convert initializer list argument to 'Matrix<double, 2, 3>'
class Matrix {
^
1704186652/source.cpp:12:3: note: candidate constructor not viable: cannot convert initializer list argument to 'const array2d<double, 2UL, 3UL>' (aka 'const std::__1::array<std::__1::array<double, 2>, 3>')
Matrix(const array2d<T, N, M>& value) : value(value) {}
^
For starters, you have your dimensions reversed.
If you expand your template, this becomes
Or a three element array with each element being two values, and not a two element array with three values per element.
Braced initialization lists, with nested constructors and parameters, sometimes can be a challenge to decipher, and quite often you just have to poke and scribble randomly until it compiles. The following compiles with gcc 10.2, and checked with a debugger that everything is where it should be. My best attempt at explaining the braces: