Limited primitives

Is there something like restricted primitives in Java or C ++? What I want is a variable that acts like a float or double, except that it has a minimum and maximum level of customization.

So, for example, if I were to set a floating point variable like this to be bound between 0 and 100, I could try to set it to any number, and generally use it exactly like a primitive , except that when the value assigned to it is greater than the allowed maximum, it will take the maximum, and when it is less than the minimum, it will take the minimum. I want to be able to do basic operations on it like addition, multiplication and subtraction - in particular, using operators that I will use for similar normal variables.

Do they exist somewhere in some library?

+3


source to share


2 answers


Well, for that you can create a class like this (in C ++). The basic design would be like this: -

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 can convert it to a template to support other data types.

+3


source


There are no such Pigs. Also, Java doesn't allow operator overloading, so you can never write something like:

myBoundedInt i = 13;

      

But rather:



myBoundedInt i = new myBoundedInt(13);
//...
i.setValue(42);

      

As far as I know, Dlang has built in assertions for classes to ensure that certain conditions are met throughout the life of an object. You might want to look into this.

+1


source







All Articles