prepend.hpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*!
  2. @file
  3. Defines `boost::hana::prepend`.
  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_PREPEND_HPP
  9. #define BOOST_HANA_PREPEND_HPP
  10. #include <boost/hana/fwd/prepend.hpp>
  11. #include <boost/hana/at.hpp>
  12. #include <boost/hana/concat.hpp>
  13. #include <boost/hana/concept/monad_plus.hpp>
  14. #include <boost/hana/concept/sequence.hpp>
  15. #include <boost/hana/config.hpp>
  16. #include <boost/hana/core/dispatch.hpp>
  17. #include <boost/hana/core/make.hpp>
  18. #include <boost/hana/length.hpp>
  19. #include <boost/hana/lift.hpp>
  20. #include <cstddef>
  21. #include <utility>
  22. BOOST_HANA_NAMESPACE_BEGIN
  23. //! @cond
  24. template <typename Xs, typename X>
  25. constexpr auto prepend_t::operator()(Xs&& xs, X&& x) const {
  26. using M = typename hana::tag_of<Xs>::type;
  27. using Prepend = BOOST_HANA_DISPATCH_IF(prepend_impl<M>,
  28. hana::MonadPlus<M>::value
  29. );
  30. #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
  31. static_assert(hana::MonadPlus<M>::value,
  32. "hana::prepend(xs, x) requires 'xs' to be a MonadPlus");
  33. #endif
  34. return Prepend::apply(static_cast<Xs&&>(xs), static_cast<X&&>(x));
  35. }
  36. //! @endcond
  37. template <typename M, bool condition>
  38. struct prepend_impl<M, when<condition>> : default_ {
  39. template <typename Xs, typename X>
  40. static constexpr auto apply(Xs&& xs, X&& x) {
  41. return hana::concat(hana::lift<M>(static_cast<X&&>(x)),
  42. static_cast<Xs&&>(xs));
  43. }
  44. };
  45. template <typename S>
  46. struct prepend_impl<S, when<Sequence<S>::value>> {
  47. template <typename Xs, typename X, std::size_t ...i>
  48. static constexpr auto prepend_helper(Xs&& xs, X&& x, std::index_sequence<i...>) {
  49. return hana::make<S>(
  50. static_cast<X&&>(x), hana::at_c<i>(static_cast<Xs&&>(xs))...
  51. );
  52. }
  53. template <typename Xs, typename X>
  54. static constexpr auto apply(Xs&& xs, X&& x) {
  55. constexpr std::size_t N = decltype(hana::length(xs))::value;
  56. return prepend_helper(static_cast<Xs&&>(xs), static_cast<X&&>(x),
  57. std::make_index_sequence<N>{});
  58. }
  59. };
  60. BOOST_HANA_NAMESPACE_END
  61. #endif // !BOOST_HANA_PREPEND_HPP