EXT C++ Library - limited

The ext::limited template is used to limit range of values of its underlying integral type and ensuring that the value will never overflow nor underflow. The value is bound to lower or upper limit respectively instead.


Interface:

template <typename T, T _lo, T _hi>
class ext::limited {
    public:
        // constructors
        limited ();

        template <typename U>
        explicit limited (const U &);

        // assignment
        template <typename U>
        limited & operator = (const U &);

        // convertible to underlying type
        operator T () const;

        // efficiently limited in/decrementing
        const limited & operator ++ ();
        const limited & operator -- ();
        const T operator ++ (int);
        const T operator -- (int);

        template <typename U> limited & operator += (const U &);
        template <typename U> limited & operator -= (const U &);
};

Details:

The limited variable can be assigned any value or be involved in numeric expressions, yet still retaining its value in declared range. Note that reversal of the boundaries results in increment and decrement operations behaving reversely. This is intended behavior.

Examples:

#include <ext/c++>

int main () {
    ext::limited <int, -7, +7> i = 0;

    i += 100;// i == 7
    i -= 100;// i == -7
    i = 3 * (i + 10);// i == 7

    return 0;
};

Remarks

Note that operators += and -= are templated to avoid otherwise possible early truncation of the parameter to the underlying type.

See EXT C++ Library testsuite for more detailed example.


[index]