std::initializer list from already existing std::array without enumerating each element

限于喜欢 提交于 2020-01-05 04:27:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!