C++ 11對於距離積分序列沒有基於範圍的循環。基於範圍的循環C++ 11用於範圍(L,R)
for(auto e : {0..10}) // wouldn't compile!!!
所以我只是決定模擬它。
template< class T , bool enable = std::is_integral<T>::value >
struct range_impl
{
struct iterator
{
constexpr T operator *()const noexcept { return value; }
iterator& operator ++()noexcept { ++value; return *this; }
friend
constexpr bool operator != (const iterator & lhs, const iterator rhs) noexcept
{
return lhs.value != rhs.value;
}
T value;
};
constexpr iterator begin()const noexcept { return { first }; }
constexpr iterator end ()const noexcept { return { last }; }
T first;
T last ;
};
template< class T >
range_impl<T> range(T first , T last) noexcept
{
return {first, last};
}
int main(){
// print numbers in [ 0..10), i.e. 0 1 2 3 4 5 6 7 8 9
for(auto e : range(0,10)) std::cout << e << ' ';
std::cout << std::endl;
}
問:如何爲ForwardIterators推廣此方法?
例如:
template< class ForwardIterator, class T >
bool find(ForwardIterator first, ForwardIterator last, T const& value)
{
for(auto e: range(first, last)) if (e == v) return true;
return false;
}
那不是真的*以偏概全*它;整數不是迭代器。你基本上是用同一個名字創建一個新的函數。 –