Skip to content

Instantly share code, notes, and snippets.

@smac89
Last active May 9, 2017 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smac89/d3b6e93849a492073999d44d673df0fe to your computer and use it in GitHub Desktop.
Save smac89/d3b6e93849a492073999d44d673df0fe to your computer and use it in GitHub Desktop.
C++ range implementation
#include <iostream>
#include <type_traits>
#include <limits>
#include <stdexcept>
template <typename I>
class range_t {
static_assert(std::is_integral<I>::value, "Integer type required");
class offset {
public:
offset(I value): value(value) {}
operator I&() { return value; }
I operator *() const { return value; }
private:
I value;
};
public:
range_t(I last): range_t(0, last) {}
explicit range_t(I last, bool inc): range_t(0, last, inc) {}
explicit range_t(I start, I last): range_t(start, last, false) {}
explicit range_t(I start, I last, bool inc): start(start),
last(inc && inc && last < std::numeric_limits<I>::max() ? last + 1 : last) {
if (last < start) {
throw std::range_error("Start has to be less than or equal to last");
}
}
const offset& begin() const { return start; }
const offset& end() const { return last; }
private:
offset start, last;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment