您应该为Matrix(std::initializer_list</* here */> list); 提供确切的类型。
然后要填充数组,您需要遍历传递的列表并填充数组。 (See live online)
#include <initializer_list> // std::initializer_list
template<typename T, std::size_t R, std::size_t C>
class Matrix
{
T mArray2D[R][C]{};
public:
Matrix(const std::initializer_list<T[C]> list)
// ^^^^^ --> type of the row
{
auto iter{ list.begin() }; // returns pointer to T[C]
for (std::size_t row{}; row < R; ++row)
{
const auto& rowElements{ *iter };
for (std::size_t col{}; col < C; ++col)
{
mArray2D[row][col] = rowElements[col];
}
++iter;
}
}
};
现在在main() 中,您可以使用如下初始化列表初始化Matrix:
Matrix<int, 2, 2> mat{ {1,2}, {3,4} };
// or
// Matrix<int, 2, 2> mat = { {1,2}, {3,4} };
如果您可以使用std::array,您可以执行以下操作。 (See live online)
#include <iostream>
#include <array> // std::array
#include <initializer_list> // std::initializer_list
template<typename T, std::size_t R, std::size_t C>
class Matrix
{
using RowType = std::array<T, C>;
T mArray2D[R][C]{};
public:
Matrix(const std::initializer_list<RowType> list)
{
auto iter{ list.begin() };
for (std::size_t row{}; row < R; ++row)
{
const RowType& rowElements{ *iter };
for (std::size_t col{}; col < C; ++col)
{
mArray2D[row][col] = rowElements[col];
}
++iter;
}
}
};
如果类中的多维数组可以是std::array 类型为T 的std::array,您也可以使用std::copy。 (See live online)
#include <iostream>
#include <array> // std::array
#include <initializer_list> // std::initializer_list
#include <algorithm> // std::copy
template<typename T, std::size_t R, std::size_t C>
class Matrix
{
using RowType = std::array<T, C>;
using Array2D = std::array<RowType, R>;
Array2D mArray{ RowType{} }; // initialize the matrix
public:
Matrix(const std::initializer_list<RowType> list)
{
std::copy(list.begin(), list.end(), mArray.begin());
}
};