15

I'm reading through the draft standard for C++14 right now, and perhaps my legalese is a bit rusty, but I can't find any mention of allowing initializations like the following

std::array<int, 3> arr{1,2,3};

being legal. (EDIT: Apparently the above is legal syntax in C++11.) Currently in C++11 we have to initialize std::array as

std::array<int, 3> arr{{1,2,3}}; // uniform initialization + aggregate initialization

or

std::array<int, 3> arr = {1,2,3};

I thought I heard somewhere that they were relaxing the rules in C++14 so that we didn't have to use the double-brace method when using uniform initialization, but I can't find the actual proof.

NOTE: The reason I care about this is because I am currently developing a multi_array - type and don't want to have to initialize it like

multi_array<int, 2, 2> matrix = {
  {{ 1, 2 }}, {{ 3, 4 }}
};
bstamour
  • 7,746
  • 1
  • 26
  • 39
  • 1
    note: this discussion only applies to array of scalar type; for arrays of aggregates [see here](http://stackoverflow.com/questions/28541488/nested-aggregate-initialization-of-stdarray) – M.M May 15 '16 at 22:34
  • Possible duplicate of [When can outer braces be omitted in an initializer list?](https://stackoverflow.com/questions/11734861/when-can-outer-braces-be-omitted-in-an-initializer-list) – underscore_d Jul 23 '17 at 09:32

1 Answers1

17

Actually you can write the following in C++11 also:

std::array<int, 3> arr{1,2,3};

It is completely valid syntax.

What is not allowed in C++11 though is something like this case (see that topic; I don't want to write this here again, it is a long post). So if you ask that then, yes, we can omit the extra braces in C++14. This is the proposal:

  • Uniform initialization for arrays and class aggregate types

  • The introduction says

    This document proposes a slight relaxation of the rules for eliding braces from aggregate initialization in order to make initialization of arrays and class aggregates more uniform. This change is required in order to support class aggregate types with a single member subaggregate that behave similarly to their array counterparts (i.e. std::array).

Hope that helps.

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Thanks a bunch. Looking forward to when I can use it, now :-) – bstamour Sep 13 '13 at 18:28
  • 2
    The [cppreference page](http://en.cppreference.com/w/cpp/container/array) says that `std::array arr{1,2,3};` is not valid in C++11. (it may be wrong) – M.M May 15 '16 at 22:28
  • The 'this case' topic you link says, like cppreference, that `std::array arr{1,2,3}` is **not** valid syntax in C++11, as the rules were relaxed only in C++14. – MicroVirus Feb 01 '18 at 15:32
  • That proposal was never adopted. Instead, the preexisting brace elision rules [were generalized](http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2012/n3367.html#1270) to support this case. – Davis Herring Aug 12 '20 at 23:36