Search code examples
c++initializationstdarrayaggregate-initialization

C++: array<> too many initializers


The following code is returning the compilation error below. I'm stuck understanding how there are too many initializers. This code works using vector<X>. Does anyone know why the error is being reported and how to resolve? Thanks

#include <iostream>
#include <array>
using namespace std;

struct X {
    int x, y;
};

int main(int argc, char *argv[])
{
    array<X,2> a0 = {{0,1}, {2,3}};

    for (auto& p : a0) {
        cout << p.x << endl;
        cout << p.y << endl;
    }

    return 0;
}

Compilation:

g++ -pedantic -Wall test116.cc && ./a.out
test116.cc: In function ‘int main(int, char**)’:
test116.cc:11:34: error: too many initializers for ‘std::array<X, 2>’
     array<X,2> a0 = {{0,1}, {2,3}};

Solution

  • Try

    array<X,2> a0 = {{{0,1}, {2,3}}};
    

    Note the extra set of braces.

    It seems a bit odd but it's this way because the only member of array is the actual array:

    template <class T, size_t N>
    class array {
        T val[N];
        // ...
    };
    

    The constructors are all implicitly defined so that array ends up being a trivially constructable type.