1

Possible Duplicate:
When can outer braces be omitted in an initializer list?

I'm using std::array in Visual Studio 2010, which is actually std::tr1::array and I'm running into an annoying issue. I have a function which takes an array as an argument, for instance.

void do_something(std::tr1::array<int, 5> data)

Calling the function like do_something({1,2,3}); doesn't work and results in a compiler error, however

std::tr1::array<int, 5> data = {1,2,3};
do_something(data);

does. I don't really see why the former wouldn't work. The errors I get tell me I'm missing a ) before the {. This leads me to believe it's not expecting an initialization list, but I don't see why not. Am I misusing initialization lists?

edit: std::tr1::array isn't necessary, std::array works fine..

Community
  • 1
  • 1
user1520427
  • 1,345
  • 1
  • 15
  • 27

2 Answers2

3

Try this

do_something({{1,2,3}});

std::array uses 2 sets of braces to initialize, but in certain cases (such as that example you posted) you can elide the outer spurious braces. This might help: C++11: Correct std::array initialization?

Community
  • 1
  • 1
Pubby
  • 51,882
  • 13
  • 139
  • 180
3

The extra braces is needed because std::array is an aggregate and POD, unlike other containers in the standard library. std::array doesn't have user-defined constructor. It's first data member is an array of size N (which you pass as template argument), and this member is directly initialized with initializer. The extra braces is needed for the internal array which is directly being initialized.

Think of this as:

struct A
{
     int data[2];
};

How many braces you need when you create an instance of A ?

A a{1,2};      //wrong as per the Standard (the compiler might allow it)
A b{ {1,2 } }; //correct

In b, the outer pair of {} is used for the struct, and inner pair of {} is used for the member-array.

Hope that helps.

Nawaz
  • 353,942
  • 115
  • 666
  • 851