Not the shortest, but the coolest way to do this is to declare an array with all possible values uint8_t
and iterate over it.
#include <iostream>
#include <cstdint>
#include <limits>
namespace detail {
template<typename int_t, int_t cnt, bool not_done, int_t... rest>
struct range_impl {
static constexpr auto& value = range_impl<int_t, cnt - 1,
(cnt - 1) != std::numeric_limits<int_t>::min(), cnt, rest...>::value;
};
template<typename int_t, int_t cnt, int_t... rest>
struct range_impl<int_t, cnt, false, rest...> {
static constexpr int_t value[] = { cnt, rest... };
};
template<typename int_t, int_t cnt, int_t... rest>
constexpr int_t range_impl<int_t, cnt, false, rest...>::value[];
}
template<typename int_t>
struct range : public detail::range_impl<int_t, std::numeric_limits<int_t>::max(), true> {};
int main(int argc, char** argv) {
for(uint8_t i: range<uint8_t>::value) {
std::cout << (int) i << std::endl;
}
for(int8_t i: range<int8_t>::value) {
std::cout << (int) i << std::endl;
}
}
The structure range
generates an array at compile time. This code can be used for any integer type.
source
share