1

My foo class needs a static C++ array as a private member that I eventually declared this way :

class Foo : public Bar {

private:

    constexpr static array<int, 18> rouges = {1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36};
    // ...
}

but the compiler throws

error: array must be initialized with a brace-enclosed initializer
error: too many initializers for 'const std::array<int, 18u>'

Funny thing my array size is exactly 18 elements here and if I declare it array<int, 500> I still get the too many initializers error. As for the brace-enclosed initializer error, I don't understand what the compiler expects to read.

I documented myself by looking into Stroustrup's A Tour of C++ (11.3.1 array) but I don't see how he did it differently that I did. Alternatively, removing the constexpr static keywords doesn't get rid of the errors.

Thanks for your insight.

PinkTurtle
  • 6,942
  • 3
  • 25
  • 44

1 Answers1

0

Use one more pair of braces

constexpr static array<int, 18> rouges = { { 1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36 } };
    // ...

In fact there are two aggregates one of which is ecnlosed in other.

The initialization of std;:array is defined like (23.3.2.1 Class template array overview)

2 An array is an aggregate (8.5.1) that can be initialized with the syntax array a = { initializer-list }; where initializer-list is a comma-separated list of up to N elements whose types are convertible to T.

And (8.5.1 Aggregates)

11 Braces can be elided in an initializer-list as follows. If the initializer-list begins with a left brace, then the succeeding comma-separated list of initializer-clauses initializes the members of a subaggregate; it is erroneous for there to be more initializer-clauses than members.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Well that worked but... why ?! Can you please elaborate ? All I do see here in a 1-dimensionnal list of ints. – PinkTurtle Apr 12 '15 at 19:26
  • I am confused because *Stroustrup's A Tour of C++* (11.3.1 `array`) defines it : `array a1 = {1,2,3}`. @DeepBlackDwarf thanks for the link. I guess then that the error is compiler dependant then ? I did not get a warning but a real error at my attempt. – PinkTurtle Apr 12 '15 at 19:42
  • @PinkTurtle I think that the C++ Standard could be more clear relative to this question. – Vlad from Moscow Apr 12 '15 at 19:49
  • 1
    @PinkTurtle possibly related: http://stackoverflow.com/questions/16985687/brace-elision-in-stdarray-initialization – eerorika Apr 12 '15 at 19:55