replicate.hpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*!
  2. @file
  3. Defines `boost::hana::replicate`.
  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_REPLICATE_HPP
  9. #define BOOST_HANA_REPLICATE_HPP
  10. #include <boost/hana/fwd/replicate.hpp>
  11. #include <boost/hana/concept/integral_constant.hpp>
  12. #include <boost/hana/concept/monad_plus.hpp>
  13. #include <boost/hana/config.hpp>
  14. #include <boost/hana/core/dispatch.hpp>
  15. #include <boost/hana/core/make.hpp>
  16. #include <boost/hana/cycle.hpp>
  17. #include <boost/hana/lift.hpp>
  18. #include <cstddef>
  19. #include <utility>
  20. BOOST_HANA_NAMESPACE_BEGIN
  21. //! @cond
  22. template <typename M>
  23. template <typename X, typename N>
  24. constexpr auto replicate_t<M>::operator()(X&& x, N const& n) const {
  25. using Replicate = BOOST_HANA_DISPATCH_IF(replicate_impl<M>,
  26. hana::MonadPlus<M>::value &&
  27. hana::IntegralConstant<N>::value
  28. );
  29. #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
  30. static_assert(hana::MonadPlus<M>::value,
  31. "hana::replicate<M>(x, n) requires 'M' to be a MonadPlus");
  32. static_assert(hana::IntegralConstant<N>::value,
  33. "hana::replicate<M>(x, n) requires 'n' to be an IntegralConstant");
  34. #endif
  35. return Replicate::apply(static_cast<X&&>(x), n);
  36. }
  37. //! @endcond
  38. template <typename M, bool condition>
  39. struct replicate_impl<M, when<condition>> : default_ {
  40. template <typename X, typename N>
  41. static constexpr auto apply(X&& x, N const& n) {
  42. return hana::cycle(hana::lift<M>(static_cast<X&&>(x)), n);
  43. }
  44. };
  45. template <typename S>
  46. struct replicate_impl<S, when<Sequence<S>::value>> {
  47. template <typename X, std::size_t ...i>
  48. static constexpr auto replicate_helper(X&& x, std::index_sequence<i...>)
  49. { return hana::make<S>(((void)i, x)...); }
  50. template <typename X, typename N>
  51. static constexpr auto apply(X&& x, N const&) {
  52. constexpr std::size_t n = N::value;
  53. return replicate_helper(static_cast<X&&>(x),
  54. std::make_index_sequence<n>{});
  55. }
  56. };
  57. BOOST_HANA_NAMESPACE_END
  58. #endif // !BOOST_HANA_REPLICATE_HPP