Guest User

Untitled

a guest
Oct 21st, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include<type_traits>
  4.  
  5. namespace range
  6. {
  7. namespace detail
  8. {
  9. //イテレーター
  10. template<class It>
  11. class WithIndexIterator
  12. {
  13. using value_type = std::remove_reference_t<decltype(*std::declval<It&>())>;
  14.  
  15. private:
  16. It m_iterator;
  17. std::size_t m_index;
  18. public:
  19. WithIndexIterator(It it, std::size_t index) :
  20. m_iterator(it),
  21. m_index(index)
  22. {}
  23. decltype(auto) operator *()const
  24. {
  25. struct
  26. {
  27. value_type& value;
  28. const std::size_t index;
  29. }ret{ *m_iterator,m_index };
  30. return ret;
  31. }
  32. decltype(auto) operator ->()const
  33. {
  34. return &*(*this);
  35. }
  36. WithIndexIterator& operator ++()
  37. {
  38. ++m_iterator;
  39. ++m_index;
  40. return *this;
  41. }
  42. bool operator !=(const WithIndexIterator& other)const
  43. {
  44. return m_iterator != other.m_iterator;
  45. }
  46. };
  47.  
  48. template<class T, bool isConst = false>
  49. class WithIndexRange
  50. {
  51. using iterator = std::conditional_t<isConst, decltype(std::declval<T&>().cbegin()), decltype(std::declval<T&>().begin())>;
  52. private:
  53. T& m_range;
  54. public:
  55.  
  56. WithIndexRange(T& range) :
  57. m_range(range)
  58. {}
  59.  
  60. WithIndexIterator<iterator> begin()const
  61. {
  62. return { m_range.begin(),0 };
  63. }
  64. WithIndexIterator<iterator> end()const
  65. {
  66. return { m_range.end() , m_range.size() };
  67. }
  68. };
  69.  
  70. //生配列への特殊化
  71. template<class T, int N, bool isConst>
  72. class WithIndexRange<T(&)[N], isConst>
  73. {
  74. using iterator = std::conditional_t<isConst, const T*, T*>;
  75.  
  76. private:
  77. iterator m_begin;
  78. iterator m_end;
  79. std::size_t m_size;
  80. public:
  81.  
  82. WithIndexRange(T(&range)[N]) :
  83. m_begin(range),
  84. m_end(&range[N]),
  85. m_size(N)
  86. {}
  87.  
  88. WithIndexIterator<iterator> begin()const
  89. {
  90. return { m_begin,0 };
  91. }
  92. WithIndexIterator<iterator> end()const
  93. {
  94. return { m_end ,N - 1 };
  95. }
  96. };
  97. }
  98. constexpr struct WithIndex_t
  99. {
  100. template<class T>
  101. friend detail::WithIndexRange<T> operator ,(T&& v, WithIndex_t)
  102. {
  103. return detail::WithIndexRange<T>(v);
  104. }
  105. }with_index;
  106. constexpr struct WithIndexConst_t
  107. {
  108.  
  109. template<class T>
  110. friend detail::WithIndexRange<T, true> operator ,(T&& v, WithIndexConst_t)
  111. {
  112. return detail::WithIndexRange<T, true>(v);
  113. }
  114.  
  115. }with_index_const;
  116.  
  117. }
Add Comment
Please, Sign In to add comment