Std :: a list of initializers from an existing std :: array without listing each element

Suppose I have a class with the following constructor:

class Foo { Foo(std::initializer_list<uin8_t> args) { .... } } 

and I have the following array: std::array<uint8_t, 6> bar .

Now I would like to create an off foo object with an array bar . Is there any other way to do this as follows:

 Foo f (bar[0], bar[1], bar[2], bar[3], bar[4], bar[5]); 

This method seems a bit complicated, and it looks like it's not the way it should be.

So, can I create a std::initializer list from an existing array without listing each element of the array?

+1
c ++ arrays initializer-list
source share
2 answers

No, you cannot do this. This API, which accepts only initializer_list and is not able to accept, say, a pair of iterators or a pointer plus size, is insufficient. You will almost never see an API like that.

+2
source share

since you cannot change "Foo", you can create your own make_foo method, which automatically extends the array:

 struct Foo { Foo(std::initializer_list<int> args) {} }; template <std::size_t N, std::size_t... Is> auto make_foo(std::array<int, N>& arr, std::index_sequence<Is...>) -> Foo { return Foo{arr[Is]...}; } template <std::size_t N> auto make_foo(std::array<int, N>& arr) -> Foo { return make_foo(arr, std::make_index_sequence<N>{}); } auto test() { std::array<int, 4> arr = {{1, 2, 3, 4}}; auto foo = make_foo(arr); } 
+2
source share

All Articles