This header file makes simple integers iterable. Note that it works only on C++11 or above.
Usage:
#include "num_range.h"
for (int i : 3) cout << i << endl;
Output: 0 1 2
Implementation note:
This code is far too generic. We only need DerefableInt
.
The templates are there for no practical reason.
Cons: pollutes namespace std; nonstandard idiom;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #ifndef NUM_RANGE
#define NUM_RANGE
template<typename T>
struct Derefable {
const T& operator*() const { return x; }
operator T&() { return x; }
Derefable(const T& x=T{}) : x{x} { }
private:
T x;
};
namespace std {
template <typename T> Derefable<T> begin(const T&) { return {}; }
template <typename T> Derefable<T> end(const T& x) { return x; }
}
// usage example
// for (int i : 5) { ... }
#endif
|