Home >Backend Development >C++ >Can initializer lists initialize const member arrays in C 0x?
Initializer Lists for Member Arrays: A C 0x Puzzle
In C 0x, the introduction of initializer lists has opened up new possibilities for initializing data members. However, a common misconception can arise when attempting to use them with arrays of const members.
Consider the following code:
<code class="cpp">struct Foo { int const data[2]; Foo(std::initializer_list<int const>& ini) : data(ini) {} }; int main() { Foo f = {1, 3}; }</code>
Contrary to expectations, this code will fail to compile with the error:
<code class="text">incompatible types in assignment of ‘std::initializer_list<const int>’ to ‘const int [2]’</code>
The issue stems from the fact that the array member data is constant, while the initializer list ini holds non-constant values. To resolve this mismatch, the compiler would need to perform a const conversion on each value in the initializer list. However, this is not permitted by the language specs.
Variadic Template Constructor to the Rescue
Instead of using an initializer list constructor, a variadic template constructor can be employed:
<code class="cpp">struct Foo { int x[2]; template <typename... T> Foo(T... ts) : x{ts...} {} }; int main() { Foo f1(1, 2); Foo f2{1, 2}; }</code>
This constructor takes a variable number of parameters, allowing for direct initialization of the array elements. Note the use of brace-init-lists in the initialization phase {ts...}.
Non-Constant Case
If constness is not a requirement, another approach is to skip initialization in the constructor and fill the array in the function body:
<code class="cpp">struct Foo { int x[2]; Foo(std::initializer_list<int> il) { std::copy(il.begin(), il.end(), x); } };</code>
This method loses compile-time bounds checking but is still a viable option in certain situations.
The above is the detailed content of Can initializer lists initialize const member arrays in C 0x?. For more information, please follow other related articles on the PHP Chinese website!