Last active
May 9, 2017 17:04
-
-
Save smac89/d3b6e93849a492073999d44d673df0fe to your computer and use it in GitHub Desktop.
C++ range implementation
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
#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