take_front.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*!
  2. @file
  3. Defines `boost::hana::take_front` and `boost::hana::take_front_c`.
  4. Copyright Louis Dionne 2013-2022
  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_TAKE_FRONT_HPP
  9. #define BOOST_HANA_TAKE_FRONT_HPP
  10. #include <boost/hana/fwd/take_front.hpp>
  11. #include <boost/hana/at.hpp>
  12. #include <boost/hana/concept/integral_constant.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/integral_constant.hpp>
  18. #include <boost/hana/length.hpp>
  19. #include <cstddef>
  20. #include <utility>
  21. namespace boost { namespace hana {
  22. //! @cond
  23. template <typename Xs, typename N>
  24. constexpr auto take_front_t::operator()(Xs&& xs, N const& n) const {
  25. using S = typename hana::tag_of<Xs>::type;
  26. using TakeFront = BOOST_HANA_DISPATCH_IF(take_front_impl<S>,
  27. hana::Sequence<S>::value &&
  28. hana::IntegralConstant<N>::value
  29. );
  30. #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
  31. static_assert(hana::Sequence<S>::value,
  32. "hana::take_front(xs, n) requires 'xs' to be a Sequence");
  33. static_assert(hana::IntegralConstant<N>::value,
  34. "hana::take_front(xs, n) requires 'n' to be an IntegralConstant");
  35. #endif
  36. return TakeFront::apply(static_cast<Xs&&>(xs), n);
  37. }
  38. //! @endcond
  39. template <typename S, bool condition>
  40. struct take_front_impl<S, when<condition>> : default_ {
  41. template <typename Xs, std::size_t ...n>
  42. static constexpr auto take_front_helper(Xs&& xs, std::index_sequence<n...>) {
  43. return hana::make<S>(hana::at_c<n>(static_cast<Xs&&>(xs))...);
  44. }
  45. template <typename Xs, typename N>
  46. static constexpr auto apply(Xs&& xs, N const&) {
  47. constexpr std::size_t n = N::value;
  48. constexpr std::size_t size = decltype(hana::length(xs))::value;
  49. return take_front_helper(static_cast<Xs&&>(xs),
  50. std::make_index_sequence<(n < size ? n : size)>{});
  51. }
  52. };
  53. template <std::size_t n>
  54. struct take_front_c_t {
  55. template <typename Xs>
  56. constexpr auto operator()(Xs&& xs) const {
  57. return hana::take_front(static_cast<Xs&&>(xs), hana::size_c<n>);
  58. }
  59. };
  60. }} // end namespace boost::hana
  61. #endif // !BOOST_HANA_TAKE_FRONT_HPP