Re: Ranged Integers
On Sun, 2 Sep 2007 17:47:13 -0600, Jerry Coffin <jcoffin@taeus.com>
wrote:
In article <1188774365.772466.314810@o80g2000hse.googlegroups.com>,
foothompson@yahoo.com says...
is there a simple integer type library around that behaves like normal
integers, i.e has all the same operations, but except the value can
only be in a specific range, like 0 to 100, and if the value is
outside of this range, it will throw an exception or assert fail?
This might fill the bill:
<...>
Or, pressing it harder:
#include <exception>
#include <iostream>
#include <functional>
template <class T, T lower, T higher, class less=std::less<T> >
class bounded {
T val_;
bool check(T const &value) {
return less()(value, lower) || less()(upper, value);
}
void assign(T const &value) {
if (check(value))
throw std::domain_error("Out of Range");
val_ = value;
}
public:
explicit bounded(T val) {assign(val);}
bounded() :val_(
less()(T(),lower)?lower:
less()(higher,T())?higher:T()) {}
bounded(bounded const &init):val_(init.val_) {}
template<T1,T1 other_lower,T1 other_higher,less1>
bounded(
bounded<T1,other_lower,other_higher,less1>
const &init) {assign(init.val_)}
bounded &operator=(T const &v) { assign(v); return *this; }
bounded &operator=(bounded const &v) {val_=v.val_; return *this;}
template<T1,T1 other_lower,T1 other_higher,less1>
bounded& operator=(
bounded<T1,other_lower,other_higher,less1>
const &v) {assign(v.val_)}
operator T() const { return val_; }
friend std::istream &operator>>(std::istream &is, bounded &b) {
T temp;
is >> temp;
if (b.check(temp))
is.setstate(std::ios::failbit);
else
b.val_ = temp;
return is;
}
};
Just to have different types for different ranges, and faster
assignment/copy when maintining range.
Regards,
Zara