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?
T &&... initis a pack expansion that does not contain a pack, so it won't work.std::arrayis 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 sincestd::arraydoes not support initializer list assignment." So? I.e., why do you perceive this to be a problem?ArrayWrapper<int, 4> aw({1,2,3,4});? IsArrayWrapper<int, 4> aw(1,2,3,4);acceptable? How aboutArrayWrapper<int, 4> aw({{1,2,3,4}});? This smells strongly like an XY problem...std::arraysupports. As per en.cppreference.com/w/cpp/concept/SequenceContainer#cite_note-1std::arraymust support braced-init-list assignment, that is this syntax:std::array<int, 4> arr({1,2,3,4});. Sincestd::arraysupports this syntax, I want my wrapper to support this syntax as well.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...