Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize a member array with an initializer_list?

I'm getting up to speed with C++0x, and testing things out with g++ 4.6

I just tried the following code, thinking it would work, but it doesn't compile. I get the error:

incompatible types in assignment of ‘std::initializer_list<const int>’ to ‘const int [2]’

struct Foo   {     int const data[2];      Foo(std::initializer_list<int const>& ini)     : data(ini)     {}   };  Foo f = {1,3}; 
like image 379
swestrup Avatar asked Apr 05 '11 09:04

swestrup


People also ask

What is the correct way to initialize an array?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

How do you initialize all members of an array to the same value?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

How do you initialize an array in C++?

Initializing arrays But the elements in an array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}. For example: int foo [5] = { 16, 2, 77, 40, 12071 };

How will you initialize data member using constructor?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.


1 Answers

You can use a variadic template constructor instead of an initializer list constructor:

struct foo {      int x[2];      template <typename... T>      foo(T... ts) : x{ts...} { // note the use of brace-init-list     }  };  int main() {     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 } 

EDIT: If you can live without constness, another way would be to skip initialization and fill the array in the function body:

struct foo {     int x[2]; // or std::array<int, 2> x;     foo(std::initializer_list<int> il) {        std::copy(il.begin(), il.end(), x);        // or std::copy(il.begin(), il.end(), x.begin());        // or x.fill(il.begin());     } } 

This way, though, you lose the compile-time bounds checking that the former solution provides.

like image 171
JohannesD Avatar answered Sep 24 '22 13:09

JohannesD