take_back.hpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*!
  2. @file
  3. Defines `boost::hana::take_back`.
  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_TAKE_BACK_HPP
  9. #define BOOST_HANA_TAKE_BACK_HPP
  10. #include <boost/hana/fwd/take_back.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. BOOST_HANA_NAMESPACE_BEGIN
  22. //! @cond
  23. template <typename Xs, typename N>
  24. constexpr auto take_back_t::operator()(Xs&& xs, N const& n) const {
  25. using S = typename hana::tag_of<Xs>::type;
  26. using TakeBack = BOOST_HANA_DISPATCH_IF(take_back_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_back(xs, n) requires 'xs' to be a Sequence");
  33. static_assert(hana::IntegralConstant<N>::value,
  34. "hana::take_back(xs, n) requires 'n' to be an IntegralConstant");
  35. #endif
  36. return TakeBack::apply(static_cast<Xs&&>(xs), n);
  37. }
  38. //! @endcond
  39. template <typename S, bool condition>
  40. struct take_back_impl<S, when<condition>> : default_ {
  41. template <std::size_t start, typename Xs, std::size_t ...n>
  42. static constexpr auto take_back_helper(Xs&& xs, std::index_sequence<n...>) {
  43. return hana::make<S>(hana::at_c<start + 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 len = decltype(hana::length(xs))::value;
  49. constexpr std::size_t start = n < len ? len - n : 0;
  50. return take_back_helper<start>(static_cast<Xs&&>(xs),
  51. std::make_index_sequence<(n < len ? n : len)>{});
  52. }
  53. };
  54. template <std::size_t n>
  55. struct take_back_c_t {
  56. template <typename Xs>
  57. constexpr auto operator()(Xs&& xs) const {
  58. return hana::take_back(static_cast<Xs&&>(xs), hana::size_c<n>);
  59. }
  60. };
  61. BOOST_HANA_NAMESPACE_END
  62. #endif // !BOOST_HANA_TAKE_BACK_HPP