unpack_flatten.hpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*!
  2. @file
  3. Defines `boost::hana::detail::unpack_flatten`.
  4. @copyright Louis Dionne 2013-2017
  5. Distributed under the Boost Software License, Version 1.0.
  6. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
  7. */
  8. #ifndef BOOST_HANA_DETAIL_UNPACK_FLATTEN_HPP
  9. #define BOOST_HANA_DETAIL_UNPACK_FLATTEN_HPP
  10. #include <boost/hana/at.hpp>
  11. #include <boost/hana/config.hpp>
  12. #include <boost/hana/detail/algorithm.hpp>
  13. #include <boost/hana/detail/array.hpp>
  14. #include <boost/hana/length.hpp>
  15. #include <boost/hana/unpack.hpp>
  16. #include <cstddef>
  17. #include <utility>
  18. BOOST_HANA_NAMESPACE_BEGIN namespace detail {
  19. template <std::size_t ...Lengths>
  20. struct flatten_indices {
  21. // avoid empty arrays by appending 0 to `lengths`
  22. static constexpr std::size_t lengths[sizeof...(Lengths) + 1] = {Lengths..., 0};
  23. static constexpr auto flat_length =
  24. detail::accumulate(lengths, lengths + sizeof...(Lengths), 0);
  25. template <bool Inner>
  26. static constexpr auto compute() {
  27. detail::array<std::size_t, flat_length> indices{};
  28. for (std::size_t index = 0, i = 0; i < sizeof...(Lengths); ++i)
  29. for (std::size_t j = 0; j < lengths[i]; ++j, ++index)
  30. indices[index] = (Inner ? i : j);
  31. return indices;
  32. }
  33. static constexpr auto inner = compute<true>();
  34. static constexpr auto outer = compute<false>();
  35. template <typename Xs, typename F, std::size_t ...i>
  36. static constexpr decltype(auto)
  37. apply(Xs&& xs, F&& f, std::index_sequence<i...>) {
  38. return static_cast<F&&>(f)(
  39. hana::at_c<outer[i]>(hana::at_c<inner[i]>(
  40. static_cast<Xs&&>(xs)
  41. ))...
  42. );
  43. }
  44. };
  45. struct make_flatten_indices {
  46. template <typename ...Xs>
  47. auto operator()(Xs const& ...xs) const -> detail::flatten_indices<
  48. decltype(hana::length(xs))::value...
  49. >;
  50. };
  51. template <typename Xs, typename F>
  52. constexpr decltype(auto) unpack_flatten(Xs&& xs, F&& f) {
  53. using Indices = decltype(hana::unpack(xs, make_flatten_indices{}));
  54. return Indices::apply(static_cast<Xs&&>(xs), static_cast<F&&>(f),
  55. std::make_index_sequence<Indices::flat_length>{});
  56. }
  57. } BOOST_HANA_NAMESPACE_END
  58. #endif // !BOOST_HANA_DETAIL_UNPACK_FLATTEN_HPP