Using std::array with Initialization Lists: A Compiler Conundrum
While the syntax for using initialization lists with std::array may seem straightforward, some users have encountered difficulties when attempting to implement it. The example provided in the question:
<code class="cpp">std::array<std::string, 2> strings = { "a", "b" };</code>
results in a compilation error in GCC 4.6.1 due to an unexpected token before the comma. This inconsistency with the behavior of std::vector, which accepts initialization lists without issue, has led to confusion and speculation about the validity of the syntax.
Delving into the Nature of std::array
To understand this discrepancy, it is essential to examine the definition of std::array:
<code class="cpp">template<typename T, int size> struct std::array { T a[size]; };</code>
As evident from this definition, std::array is essentially a struct that encloses an array. It lacks a constructor that directly accepts an initialization list. However, according to the rules of C 11, std::array is considered an aggregate. This allows for aggregate initialization, which involves initializing the elements of the array indirectly.
Overcoming the Syntax Enigma
To successfully initialize a std::array using aggregate initialization, an additional set of curly braces is required:
<code class="cpp">std::array<std::string, 2> strings = {{ "a", "b" }};</code>
By nesting the curly braces, the compiler recognizes the intent to initialize the elements of the array within the struct. This eliminates the compilation error experienced with the first example.
GCC Bugs or Standard Irregularities?
Interestingly, the C standard implies that the extra braces could be omitted in this specific case. Therefore, it is likely that GCC 4.6.1 is experiencing a bug that prevents the proper interpretation of the simplified syntax.
The above is the detailed content of Why Does Initializing std::array with an Initialization List Cause a Compilation Error in GCC 4.6.1?. For more information, please follow other related articles on the PHP Chinese website!