I'm trying to initialize my Matrix class with std::initializer_lists. I know I can do it with std::index_sequence, but I don't know how to expand them in one statement.
This is how I do it:
template<size_t rows, size_t cols>
class Matrix {
public:
Matrix(std::initializer_list<std::initializer_list<float>> il)
: Matrix(il,
std::make_index_sequence<rows>(),
std::make_index_sequence<cols>()) {}
private:
template<size_t... RowIs, size_t... ColIs>
Matrix(std::initializer_list<std::initializer_list<float>> il,
std::index_sequence<RowIs...>,
std::index_sequence<ColIs...>)
: values_{
{
il.begin()[RowIs].begin()[ColIs]...
}...
} {}
public:
float values_[rows][cols] = {};
};
It fails on the second expansion with error Pack expansion does not contain any unexpanded parameter packs. Maybe I can somehow specify which parameter pack I want to expand?
Hope for your help!
I think the problem comes from the fact that
RowIsandColIsare expanded at the same time, i.e. both always having the same values during the initialization: 0, 1, 2...You can check here that your current output (after fixing the compiler error) would be something like
[[1.1, 5.5, 9.9], [0, 0, 0], [0, 0, 0]]for the matrix below:Because you only read from
il[0,0],il[1,1], andil[2,2]in order to setvalues_.What you could do is to create a sequence with a flat index, from
0toRows*Cols - 1, and read every value fromilwithFlatIs/ColsandFlatIs%Cols:[Demo]