问题
I have a question about the use of multidimensional std::intializer_list in C++. I have a Matrix class, and I want to be able to initialize it like this:
Matrix<int, 3, 3> m({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
The constructor that I have now takes an argument of a two-dimensional initializer list, but the compiler doesn't like how I'm using it. Here's the code:
template<typename T, unsigned int rows, unsigned int cols>
Matrix<T, rows, cols>::Matrix(std::initializer_list<std::initializer_list<T> > set)
{
std::vector<std::initializer_list<T> > setVec = set;
std::vector<std::vector<T> > v;
for (std::vector<std::initializer_list<T> >::iterator i = setVec.begin(); i != setVec.end(); i++)
{
v.push_back(std::vector<T>(*i));
}
this->matrixData = new T*[rows];
for (unsigned int i = 0; i < rows; i++)
{
this->matrixData[i] = new T[cols];
for (unsigned int j = 0; j < cols; j++)
{
this->matrixData[i][j] = v[i][j];
}
}
}
And here's the error:
..\/utils/Matrix.h:138:7: error: need 'typename' before 'std::vector<std::initializer_list<_CharT> >::iterator' because 'std::vector<std::initializer_list<_CharT> >' is a dependent scope
How do I get rid of that error? Is there a way to restructure it so I don't have to make that ugly vector of an initializer list or something?
回答1:
Yes, as the error message says, you need to write typename
here:
typename std::vector<std::initializer_list<T>>::iterator i = setVec.begin();
It is because iterator
is a dependent name. Read this for detail explanation:
- Where and why do I have to put the "template" and "typename" keywords?
If your compiler supports auto
introduced by C++11, then you could write this:
auto i = setVec.begin();
which is much better syntax. Since you're already using C++11 feature such as std::initializer_list
, you should start using auto
wherever it makes your life easy.
来源:https://stackoverflow.com/questions/9858968/using-multidimensional-stdinitializer-list