问题
Lets assume that 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 object off foo
with the bar
array. Is there an other way as doing it in the follwing way:
Foo f (bar[0], bar[1], bar[2], bar[3], bar[4], bar[5]);
This way seems a bit complicated and it feels like this is not the way it should be.
So, can I create a std::initializer list
from an already existing array, without enumerating each array element?
回答1:
No, you can't do it. This API which only accepts an initializer_list
and has no facility to accept, say, a pair of iterators, or a pointer plus a size, is deficient. You'll virtually never see an API like this in the wild.
回答2:
since you cannot modify "Foo" you can create your own make_foo
method that automatically expands 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);
}
来源:https://stackoverflow.com/questions/45546362/stdinitializer-list-from-already-existing-stdarray-without-enumerating-each