Looping on a closed range

Posted by AProgrammer on Stack Overflow See other posts from Stack Overflow or by AProgrammer
Published on 2010-03-16T19:19:08Z Indexed on 2010/03/16 19:21 UTC
Read the original article Hit count: 237

Filed under:

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.

© Stack Overflow or respective owner

Related posts about c++