Quick Q: vector of vector does not convert brace encloser list

Save to:
Instapaper Pocket Readability

Quick A: The constructor needs an extra {} pair.

Recently on SO:

vector does not convert brace encloser list

You have two options:

  1. add a constructor taking std::initializer_list<std::initializer_list<T>>
  2. eclose the init expression with another set of {} i.e.
Matrix<double> a{{

    { 17,    24,    1},

    { 23,    5,     7 },

    {  4,     6,    13 }

}};

Ok, I'll try a little explanation of what is going on here:

If there is no constructor taking a std::initializer_list then the outermost {} are always opening and closing the constructor call if you will, and not part of what you actually pass to the constructor.

Matrix<double> a{ {1, 2}, {3, 4} };
                ^ ^~~~~~~~~~~~~~ ^
                |  2 parameters  |
                |                |
                |                |
            opening            closing

As you can see this is taken as a constructor with 2 parameters, in this case 2 initializer_lists.

This is why you need another set of {}:

Matrix<double> a{ {{1, 2}, {3, 4}} };
                ^ ^~~~~~~~~~~~~~~~ ^
                |  1 parameter     |
                |                  |
                |                  |
            opening            closing

In order for the outermost {} to be considered an initializer_list then the constructor needs to have an overload taking a initializer_list. That is what is happening in the std::vector case.

Add a Comment

You must sign in or register to add a comment.

Comments (0)

There are currently no comments on this entry.