Looping on a closed range
- by AProgrammer
How would you fix this code?
template <typename T> void closed_range(T begin, T end)
{
for (T i = begin; i <= end; ++i) {
// do something
}
}
T is constrained to be an integer type, can be the wider of such types and can be signed or unsigned
begin can be numeric_limits<T>::min()
end can be numeric_limits<T>::max() (in which case ++i will overflow in the above code)
I've several ways, but none I really like.