Is it possible to create a class that contains an int that can only take values of [0,1,2,3,4,5,6]? I mean, like a class that automatically changes the value of that int if it gets out of that range?
I'm new with classes so my idea would be to write something like this:
1 2 3 4 5 6 7
class zerotosix_t{
public:
unsignedint x;
if(x > 6)
x %= 7;
};
But this obviously isn't the right way.
How can I do this?
You may want to add some C++ operators to your class ensuring values staying in range. F.e. assignment operators (operator=, operator+=, ...), increment and decrement operators (operator++, ...), ...
@tcs: your code does not fully satisfies OP needs:
like a class that automatically changes the value of that int if it gets out of that range?
//...
1 2
if(x > 6)
x %= 7;
Wrap number around instead of throwing exception
Here is an (imperfect) example of templated class which does that. You still need to implement rest of the assigment family operators and increment/decrement. ALso for fun you can try to make it work with all ranges (currently not all ranges supported) and support different types.
@MiiNiPaa: Slight mistake:
Line 14, initialize it with L.
this allows for ranges not including 0 to be correctly default-constructed.
In your example, the first X will print 0, but it must be in range 1-6.
Initialization with L is a good idea too, I thought about it (and about ditching default constructor completely or disabling it for ranges not including 0) but decided to be consistent with int initialization.