Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a std::array-like container with a C++11 initializer_list

The only and imo very inconvenient caveat of std::array is that it can't deduce its size from the initializer list like built-in C arrays, it's size must be passed as a template.

Is it possible to implement a std::array-like container (a thin wrapper around a built-in C array) with a C++11 initializer_list?

I ask because, unlike std::array, it would automatically deduce the size of the array from the initializer list which is a lot more convenient. For example:

// il_array is the hypothetical container
// automatically deduces its size from the initalizer list 
il_array <int> myarr = {2, 4, 6, 7, 8}; 

We would also want to provide a constructor to specify the size if an initializer list was not provided. For example:

// construct a fixed size array of size 10
il_array <int> myarr2 (10); 

This would also make the container more consistent with the other standard containers e.g. vector, deque and list.

To the best of my knowledge it isn't possible as the wrapped C-array e.g. T elems [size], must have constant size and initializer_list's size() member function isn't constant.

Also, I was wondering if was possible to implement such a container using a variadic template although from what I've read I don't think it's possible.

like image 643
Ricky65 Avatar asked Aug 13 '11 12:08

Ricky65


1 Answers

I think you are out of luck here. The great advantage of std::array is that it is a POD and can be statically initialized.

If you have a container with a constructor taking a std::initializer_list, it would have to copy the values (unless it is just a constant reference to the initializer, which isn't very useful).

like image 131
Bo Persson Avatar answered Sep 25 '22 08:09

Bo Persson