Looking out for a program in C++ that implements a restricted integer.
Printable View
Looking out for a program in C++ that implements a restricted integer.
You mean, an integer that can only store a range of values?
Well, there are lots of ways you could do this. You could simply restrict the range of a number by using modulus or some such every time it was assigned to, for example. You could throw an exception when the integer got out of range. You could wrap it all up into a class to make things easier . . . .
Why do you want to know? What have you tried? Is this homework? Or are you just curious?
A restricted integer is one that has a limited domain. E.g. if you define a variable x of type restricted integer, this would have constraints as defined in your class, such as the number can’t exceed 1000.
Out of curiosity, just looking out for a program
I think one way would be a class. Overload appropriate operators to make it act like a normal integer, but assert or throw errors if it exceeds range or limitations.
or wrap around like a native type would =).Quote:
assert or throw errors if it exceeds range or limitations.
Don't forget to attempt the code first and post what you've got (preferably your own code and not code you find on the internet).
I have written such a class which you can find here:
http://homepages.ihug.co.nz/~aurora7...ul_Classes.htm
It's called RangedInteger, and throws exceptions when you try and give it a number outside the range. Let me know if you find any bugs.
Feel free to fix the crappy exception handling. It's not something I've worked on recently. You use it like this:
Code:try {
rangedInteger<1, 1000> r;
r = 500;
r *= 3; // throws
} catch(...)
{
}