This might be an odd question, but how does one nicely loop over ALL values of a type. In particular the standard integral types such as unsigned short. A normal for loop construct presents a difficulty: what condition to use to exit the loop - because all values are valid.
Of course, there are several ways to get the job done. Exit on the last value then handle that after the loop. Use a bigger int to count. The question is, is there a more elegant way?
If you want a pretty solution you can do this:
for(auto x : everyvalue<short>()) {
std::cout << x << '\n';
}
Where everyvalue is:
#include <limits>
template<typename T>
struct everyvalue {
struct iter {
T x;
bool flag;
inline iter operator++() {
if(x == std::numeric_limits<T>::max())
flag = true;
else
++x;
return *this;
}
inline T operator*() { return x;}
inline bool operator!=(iter& i) {return flag != i.flag;}
// note: missing some iterator requirements, still should work
};
inline iter begin() { return iter{std::numeric_limits<T>::min(),0}; }
inline iter end() { return iter{std::numeric_limits<T>::max(),1}; }
};
Otherwise a simple break would be preferred.
I worried about this very same issue once, and this is the best I could think of:
unsigned char c = 0;
do
{
printf("%d ", (int)c); //or whatever
} while (++c != 0);
One of the very few cases where I find the do..while syntax useful.
Note that technically it is only valid for unsigned types, as I am relying on the wrapping of values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With