ClickHouse/libs/libcommon/include/ext/range.h

46 lines
1.5 KiB
C++
Raw Normal View History

2015-10-05 00:33:43 +00:00
#pragma once
#include <type_traits>
#include <utility>
#include <iterator>
2017-06-13 02:30:24 +00:00
#include <boost/iterator/counting_iterator.hpp>
2015-10-05 00:33:43 +00:00
/** \brief Numeric range iterator, used to represent a half-closed interval [begin, end).
* In conjunction with std::reverse_iterator allows for forward and backward iteration
* over corresponding interval. */
2015-10-05 00:33:43 +00:00
namespace ext
{
2017-06-13 02:30:24 +00:00
template <typename T>
using range_iterator = boost::counting_iterator<T>;
2015-10-05 00:33:43 +00:00
/** \brief Range-based for loop adapter for (reverse_)range_iterator.
2017-06-13 02:45:08 +00:00
* By and large should be in conjunction with ext::range and ext::reverse_range.
*/
template <typename T>
2017-06-13 02:30:24 +00:00
struct range_wrapper
{
using value_type = typename std::remove_reference<T>::type;
2017-06-13 02:45:08 +00:00
using iterator = range_iterator<value_type>;
2015-10-05 00:33:43 +00:00
2017-06-13 02:45:08 +00:00
value_type begin_;
value_type end_;
2015-10-05 00:33:43 +00:00
2017-06-13 02:45:08 +00:00
iterator begin() const { return iterator(begin_); }
iterator end() const { return iterator(end_); }
};
2015-10-05 00:33:43 +00:00
/** \brief Constructs range_wrapper for forward-iteration over [begin, end) in range-based for loop.
* Usage example:
* for (const auto i : ext::range(0, 4)) print(i);
* Output:
2017-06-13 02:45:08 +00:00
* 0 1 2 3
*/
template <typename T1, typename T2>
inline range_wrapper<typename std::common_type<T1, T2>::type> range(T1 begin, T2 end)
{
using common_type = typename std::common_type<T1, T2>::type;
return { static_cast<common_type>(begin), static_cast<common_type>(end) };
}
2015-10-05 00:33:43 +00:00
}