distance.hpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright (C) 2017 Michel Morin.
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_ITERATOR_DISTANCE_HPP
  7. #define BOOST_ITERATOR_DISTANCE_HPP
  8. #include <boost/config.hpp>
  9. #include <boost/iterator/iterator_categories.hpp>
  10. #include <boost/iterator/iterator_traits.hpp>
  11. namespace boost {
  12. namespace iterators {
  13. namespace detail {
  14. template <typename SinglePassIterator>
  15. inline BOOST_CXX14_CONSTEXPR typename iterator_difference<SinglePassIterator>::type
  16. distance_impl(
  17. SinglePassIterator first
  18. , SinglePassIterator last
  19. , single_pass_traversal_tag
  20. )
  21. {
  22. typename iterator_difference<SinglePassIterator>::type n = 0;
  23. while (first != last) {
  24. ++first;
  25. ++n;
  26. }
  27. return n;
  28. }
  29. template <typename RandomAccessIterator>
  30. inline BOOST_CXX14_CONSTEXPR typename iterator_difference<RandomAccessIterator>::type
  31. distance_impl(
  32. RandomAccessIterator first
  33. , RandomAccessIterator last
  34. , random_access_traversal_tag
  35. )
  36. {
  37. return last - first;
  38. }
  39. }
  40. namespace distance_adl_barrier {
  41. template <typename SinglePassIterator>
  42. inline BOOST_CXX14_CONSTEXPR typename iterator_difference<SinglePassIterator>::type
  43. distance(SinglePassIterator first, SinglePassIterator last)
  44. {
  45. return detail::distance_impl(
  46. first, last, typename iterator_traversal<SinglePassIterator>::type()
  47. );
  48. }
  49. }
  50. using namespace distance_adl_barrier;
  51. } // namespace iterators
  52. using namespace iterators::distance_adl_barrier;
  53. } // namespace boost
  54. #endif