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

43 lines
1.5 KiB
C++
Raw Normal View History

2015-10-05 00:33:43 +00:00
#pragma once
#include <type_traits>
#include <boost/range/counting_range.hpp>
#include <boost/range/adaptor/transformed.hpp>
2017-06-13 02:30:24 +00:00
2015-10-05 00:33:43 +00:00
namespace ext
{
/// For loop adaptor which is used to iterate through a half-closed interval [begin, end).
template <typename BeginType, typename EndType>
inline auto range(BeginType begin, EndType end)
{
using CommonType = typename std::common_type<BeginType, EndType>::type;
return boost::counting_range<CommonType>(begin, end);
}
2015-10-05 00:33:43 +00:00
template <typename Type>
inline auto range(Type end)
{
return range<Type, Type>(static_cast<Type>(0), end);
}
2015-10-05 00:33:43 +00:00
/// The same as range(), but every value is casted statically to a specified `ValueType`.
/// This is useful to iterate through all constants of a enum.
template <typename ValueType, typename BeginType, typename EndType>
inline auto range_with_static_cast(BeginType begin, EndType end)
{
using CommonType = typename std::common_type<BeginType, EndType>::type;
if constexpr (std::is_same_v<ValueType, CommonType>)
return boost::counting_range<CommonType>(begin, end);
else
return boost::counting_range<CommonType>(begin, end)
| boost::adaptors::transformed([](CommonType x) -> ValueType { return static_cast<ValueType>(x); });
}
2015-10-05 00:33:43 +00:00
template <typename ValueType, typename EndType>
inline auto range_with_static_cast(EndType end)
{
return range_with_static_cast<ValueType, EndType, EndType>(static_cast<EndType>(0), end);
}
2015-10-05 00:33:43 +00:00
}