1

std::array supports aggregate initialization, but what is the problem here? If code (1) is used, both vc10.0 and g++ 4.7.2 complain that too many initializers. But if I use code (2) instead, everything is OK.

#include <array>

struct elem_t {  char c;  unsigned n;};

struct my_struct_t
{
  int i;
  // std::array<elem_t, 2> a; // (1) cause error
  // elem_t a[2]; // (2) ok
};

int main()
{
  std::array<int, 3> ai[] = {{1,2,3},{4,5,6}}; // ok

  my_struct_t var[] =
  {
    { 0, { {'a',1U}, {'b',2U}} }, // in question?
  };
}

1 Answer 1

1

Try extra braces -- you need one extra pair for the array itself:

my_struct_t var[] = { { 0, { { { 'a', 1 } } } }
                    , { 1, { { { 'c', 3 } } } }
};

//                  ^-  mystruct[]
//                     ^-  mystruct
//                         ^-  array
//                           ^-  elem_t[2]
//                             ^-  elem_t

The braces can be collapsed at the top level, but this may either be a situation where collapse isn't permitted, or compiler support may just not be there yet.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your quick reply. But this code will not be compiled if I use (1) instead of (2), gcc complains that "错误:类型‘char’的标量初始化带花括号".
sorry, I mean that "this code will not be compiled if I use (2) instead of (1) ...".
gcc complains "error: initialization 'char' type scalar with brace".
Is there any way to make the line marked with "in question" correct under both in case (1) and (2) ?
sadly, these braces depend on implementation details of std::array . An implementation of std::array is not required to have a 2-depth aggregation.
|

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.