intersperse.hpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*!
  2. @file
  3. Defines `boost::hana::intersperse`.
  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_INTERSPERSE_HPP
  9. #define BOOST_HANA_INTERSPERSE_HPP
  10. #include <boost/hana/fwd/intersperse.hpp>
  11. #include <boost/hana/at.hpp>
  12. #include <boost/hana/bool.hpp>
  13. #include <boost/hana/concept/sequence.hpp>
  14. #include <boost/hana/config.hpp>
  15. #include <boost/hana/core/dispatch.hpp>
  16. #include <boost/hana/core/make.hpp>
  17. #include <boost/hana/length.hpp>
  18. #include <cstddef>
  19. #include <utility>
  20. BOOST_HANA_NAMESPACE_BEGIN
  21. //! @cond
  22. template <typename Xs, typename Z>
  23. constexpr auto intersperse_t::operator()(Xs&& xs, Z&& z) const {
  24. using S = typename hana::tag_of<Xs>::type;
  25. using Intersperse = BOOST_HANA_DISPATCH_IF(intersperse_impl<S>,
  26. hana::Sequence<S>::value
  27. );
  28. #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
  29. static_assert(hana::Sequence<S>::value,
  30. "hana::intersperse(xs, z) requires 'xs' to be a Sequence");
  31. #endif
  32. return Intersperse::apply(static_cast<Xs&&>(xs), static_cast<Z&&>(z));
  33. }
  34. //! @endcond
  35. template <typename S, bool condition>
  36. struct intersperse_impl<S, when<condition>> : default_ {
  37. template <std::size_t i, typename Xs, typename Z>
  38. static constexpr decltype(auto)
  39. pick(Xs&&, Z&& z, hana::false_ /* odd index */)
  40. { return static_cast<Z&&>(z); }
  41. template <std::size_t i, typename Xs, typename Z>
  42. static constexpr decltype(auto)
  43. pick(Xs&& xs, Z&&, hana::true_ /* even index */)
  44. { return hana::at_c<(i + 1) / 2>(static_cast<Xs&&>(xs)); }
  45. template <typename Xs, typename Z, std::size_t ...i>
  46. static constexpr auto
  47. intersperse_helper(Xs&& xs, Z&& z, std::index_sequence<i...>) {
  48. return hana::make<S>(
  49. pick<i>(static_cast<Xs&&>(xs), static_cast<Z&&>(z),
  50. hana::bool_c<(i % 2 == 0)>)...
  51. );
  52. }
  53. template <typename Xs, typename Z>
  54. static constexpr auto apply(Xs&& xs, Z&& z) {
  55. constexpr std::size_t size = decltype(hana::length(xs))::value;
  56. constexpr std::size_t new_size = size == 0 ? 0 : (size * 2) - 1;
  57. return intersperse_helper(static_cast<Xs&&>(xs), static_cast<Z&&>(z),
  58. std::make_index_sequence<new_size>{});
  59. }
  60. };
  61. BOOST_HANA_NAMESPACE_END
  62. #endif // !BOOST_HANA_INTERSPERSE_HPP