1

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?

7
  • 5
    Why not just add a overload to the constructor set that takes a std::array? Commented Aug 7, 2017 at 12:01
  • 5
    No, it's not possible. Actually you can't explicitly create anything but an empty std::initializer_list, as there are no functionality to add elements to it. Commented Aug 7, 2017 at 12:01
  • @NathanOliver Thats just because the Foo class comes from an other API so I wanted to know if I can use this constructor in a more effective way. Commented Aug 7, 2017 at 12:06
  • 5
    As for another possible solution, rather an adding an overload for std::array, how about creating a constructor taking a generic range using iterators? Though it only works if you can actually modify the class. Commented Aug 7, 2017 at 12:07
  • @Someprogrammerdude also a good idea, but in this case I hoped that I do not have to touch the given API. But I will think about it. Thanks Commented Aug 7, 2017 at 12:08

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.