ericniebler / range-v3

Range library for C++14/17/20, basis for C++20's std::ranges
Other
4.06k stars 437 forks source link

Allow collecting into std::array if the size is known #1757

Open dingari opened 1 year ago

dingari commented 1 year ago

I couldn't find any discussion from a quick search in the issues, but have you considered collecting a result from a range into a std::array?

I understand it's not currently supported since std::array is an aggregate and doesn't have user-defined constructors to accept the ranges/iterators (beyond the obvious reason that for many ranges we can't expect to know the size at compile-time).

That being said, and while I don't know the intricacies of the ranges::to<>, nor do I have extensive knowledge of C++ templates, I toyed around and made it do what I want in a simple case (see on Compiler Explorer).

But I figured it would be good to hear from someone more experienced with the library and its internals.

brevzin commented 1 year ago

What should r | ranges::to<array<T, N>>() do if ranges::distance(r) != N?

If r is a forward range at least and the length is correct, you can implement this using adjacent_transform<N>, like so. If r is an input range, then... you'll need some more shenanigans, like at least requiring T to be movable (you can first declare an array<optional<T>, N>, copy into that, and then construct an array<T, N> from that).

But I think the bigger question is the first one: UB? throw?