2

Is it possible to pass the exact braced-init-list to std::array’s constructor? This might be necessary since std::array does not support initializer list assignment.

Trying to adapt the accepted answer of this question: How to construct std::array object with initializer list? (answer’s shortened link: https://stackoverflow.com/a/6894191/4385532 ) to my problem, I came up with the following “solution” to the problem of passing a braced-init-list to the constructor of std::array:

template<class T, std::size_t N> struct ArrayWrapper
{
    std::array<T,N> arr;
    ArrayWrapper(T &&... init) : arr{{std::forward<T>(init)...}} {}
}

I was hoping that this would allow the following syntax:

int main()
{
  ArrayWrapper<int, 4> aw{{1,2,3,4}};
  std::cout << aw.arr[2] << '\n';
}

However, I failed. This won’t compile: http://ideone.com/VJVU1X

I’m not sure what is my error. I hoped that this line

ArrayWrapper(T &&... init) : arr{{std::forward<T>(init)...}} {}

would catch the exact elements of the braced-init-list passed to ArrayWrapper’s constructor, and forward them to the constructor of std::array.

What do I fail to understand?

7
  • T &&... init is a pack expansion that does not contain a pack, so it won't work. Commented Nov 15, 2016 at 5:07
  • std::array is an aggregate – it doesn't have a constructor, and I'm not sure what documentation led you to believe that it would. "This might be necessary since std::array does not support initializer list assignment." So? I.e., why do you perceive this to be a problem? Commented Nov 15, 2016 at 11:42
  • Is the end-goal here to support specifically this syntax: ArrayWrapper<int, 4> aw({1,2,3,4});? Is ArrayWrapper<int, 4> aw(1,2,3,4); acceptable? How about ArrayWrapper<int, 4> aw({{1,2,3,4}});? This smells strongly like an XY problem... Commented Nov 15, 2016 at 11:43
  • @ildjarn I’m attempting to write a wrapper that will support every syntax std::array supports. As per en.cppreference.com/w/cpp/concept/SequenceContainer#cite_note-1 std::array must support braced-init-list assignment, that is this syntax: std::array<int, 4> arr({1,2,3,4});. Since std::array supports this syntax, I want my wrapper to support this syntax as well. Commented Nov 15, 2016 at 14:08
  • 1
    Per your edit, a constructor like ArrayWrapper(T const(&a)[N]) { std::copy(a, a+N, arr.data()); } would allow such syntax, but I've no idea if it actually has the semantics you want... Commented Nov 15, 2016 at 14:20

0

Your Answer

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