Is there anything like bounded primitives in Java or C++? What I want is a variable that acts just like a float or double, except that it has a user-settable minimum and maximum.
So for example, if I were to set up such a floating-point variable to be bound between 0 and 100, I could try to set it to any number, and generally use it just in the same fashion as I would a primitive, except that when the value assigned to it would be greater than the allowed maximum, it would assume the maximum, and when it would be less than the minimum, it would assume the minimum. I want to be able to do basic operations on it, like addition, multiplication and subtraction - particularly using the operators I would use on analogous normal variables.
Do these exist in some library somewhere?
Well you can design such a class ( in C++ ) for that. Basic design would be like:-
class Bound
{
private:
const int min = 10;
const int max = 100;
int var;
public:
Bound( int x )
{
if ( x > max )
var = max;
else if ( x < min )
var = min;
else
var = x;
}
Bound& operator == ( int x )
{
// On same line as constructor
}
};
You could convert it into template to support other data types.