Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control value assigned by operator []

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?

like image 529
geradism Avatar asked Mar 28 '17 10:03

geradism


Video Answer


1 Answers

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;
};
like image 167
Rene Avatar answered Sep 18 '22 10:09

Rene