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>'

1 Answer 1

3

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

std::array<float, 3> phis = {{1, 2, 3}};
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't explain why you can say std::array<float, 3> 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 I think you are correct as far as the standard is concerned, see the comments in this thread. You should be able to use a single set of braces, it is an issue with GCC that is being addressed (AFAIK)

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.