5

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?

2
  • 4
    Did you try actually reading the error message? Commented Mar 25, 2012 at 18:23
  • 1
    Yes, I didn't quite get what it was requesting. Commented Mar 26, 2012 at 1:25

1 Answer 1

8

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:

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.