I know how to overload operator[]
as follows :
T& operator [](int idx) {
return TheArray[idx];
}
T operator [](int idx) const {
return TheArray[idx];
}
But what I want is to control values assigned by arr[i] = value
.
I want to control value to be between 0 and 9.
Is there any syntax to do so?
You would have to write a template class that holds a reference to the element in the array (of type T), in this template you implement the assignment operator, and there you can implement your check. Then you return an object of this template class from your [] operator.
Something like this:
template< typename T> class RangeCheck
{
public:
RangeCheck( T& dest): mDestVar( dest) { }
RangeCheck& operator =( const T& new_value) {
if ((0 <= new_value) && (new_value < 9)) { // <= ??
mDestVar = new_value;
} else {
... // error handling
}
return *this;
}
private:
T& mDestVar;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With