Last active
November 3, 2017 07:47
-
-
Save xentec/a5d7686907cb3ee0963469e00e2cb4bc to your computer and use it in GitHub Desktop.
Slices, C++ style. Helper class to retain sanity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <iterator> | |
template<class Iter> | |
struct Range | |
{ | |
using value_type = typename std::iterator_traits<Iter>::value_type; | |
Range(Iter b): b(b) {} | |
Range(Iter b, Iter e): b(b), e(e) {} | |
auto begin() const -> Iter { return b; } | |
auto end() const -> Iter { return e; } | |
auto begin() -> Iter& { return b; } | |
auto end() -> Iter& { return e; } | |
auto data() -> value_type* { return &*b; } | |
auto data() const -> const value_type* { return &*b; } | |
auto size() const -> size_t { return std::distance(b,e); } | |
auto empty() const -> bool { return b == e; } | |
auto advance(size_t num = 1) -> void { std::advance(b, num); } | |
private: | |
Iter b, e; | |
}; | |
template<class I> | |
static auto range(I begin, I end) -> Range<I> | |
{ | |
return Range<I>{begin, end}; | |
} | |
template<class Container, class I = typename Container::const_iterator> | |
static auto range(const Container& c) -> Range<I> | |
{ | |
return Range<I>{c.begin(), c.end()}; | |
} | |
template<class Container, class I = typename Container::iterator> | |
static auto range(Container& c) -> Range<I> | |
{ | |
return Range<I>{c.begin(), c.end()}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment