In C 0x, you may encounter the error "incompatible types in assignment" when attempting to initialize a member array with an initializer list.
To resolve this, consider using a variadic template constructor instead:
<code class="cpp">struct foo { int x[2]; template <typename... T> foo(T... ts) : x{ts...} {} }; int main() { // Usage foo f1(1, 2); // OK foo f2{1, 2}; // Also OK foo f3(42); // OK; x[1] zero-initialized foo f4(1, 2, 3); // Error: too many initializers foo f5(3.14); // Error: narrowing conversion not allowed foo f6("foo"); // Error: no conversion from const char* to int }</code>
If preserving the 'const' status is not essential, you could alternatively employ a function to load the array values:
<code class="cpp">struct foo { int x[2]; foo(std::initializer_list<int> il) { std::copy(il.begin(), il.end(), x); } };</code>
However, this approach relinquishes compile-time bounds checking.
The above is the detailed content of How to Initialize Member Arrays with Initializer Lists in C 0x?. For more information, please follow other related articles on the PHP Chinese website!