Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bounded primitives

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?

like image 693
Abu Dhabi Avatar asked Mar 17 '26 11:03

Abu Dhabi


2 Answers

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.

like image 189
ravi Avatar answered Mar 19 '26 23:03

ravi


There are no such Buildins. In addition, Java does not permit operator overloading, so you would never be able to write something like:

myBoundedInt i = 13;

But rather:

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

As far as i know, Dlang does have builtin assertions for classes to guarantee that certain conditions are fulfilled for the whole lifespan of an object. Maybe you want to look into this.

like image 38
Turing85 Avatar answered Mar 20 '26 00:03

Turing85



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!