2

Since C++11, it is possible to initialize member variables in class definitions:

class Foo {
   int i = 3;
}

I know I can initialize an std::array like this:

std::array<float, 3> phis = {1, 2, 3};

How can I do this in a class definition? The following code gives an error:

class Foo {
    std::array<float, 3> phis = {1, 2, 3};
}

GCC 4.9.1:

error: array must be initialized with a brace-enclosed initializer 
std::array<float, 3> phis = {1, 2, 3};
                                     ^ error: too many initializers for 'std::array<float, 3ul>'
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Jan Rüegg
  • 9,587
  • 8
  • 63
  • 105

1 Answers1

3

You need one more set of braces, which is non-intuitive.

std::array<float, 3> phis = {{1, 2, 3}};
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • This doesn't explain why you can say `std::array phis = {1, 2, 3};` outside of a class definition. I would have expected brace elision to apply here too (but I'm usually wrong about this one.) – juanchopanza Oct 02 '14 at 13:09
  • @juanchopanza I think you are correct as far as the standard is concerned, see the comments in [this thread](http://stackoverflow.com/questions/8192185/using-stdarray-with-initialization-lists). You *should* be able to use a single set of braces, it is an issue with GCC that is being addressed (AFAIK) – Cory Kramer Oct 02 '14 at 13:12