c++ - range based loop C++11 for range(L,R) -
c++11 hasn't range-based-loop ranged integral sequence.
for(auto e : {0..10} ) // wouldn't compile!!!
so decided simulate it.
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; }
q: how generalize method forwarditerators?
example:
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; }
specialization
template< class iterator> struct range_impl<iterator, false> { range_impl(iterator first, iterator last) : first(first), last(last) {} constexpr iterator begin()const noexcept { return { first }; } constexpr iterator end ()const noexcept { return { last }; } iterator first; iterator last ; };
test:
int main(){ for(auto e : range(0,10) ) std::cout << e << ' '; std::cout << std::endl; const char* a[] = { "say", "hello", "to", "the", "world" }; for(auto e : range(a, + 5) ) std::cout << e << ' '; std::cout << std::endl; }
Comments
Post a Comment