How to manage the value assigned by the operator []

I know how to reload operator[]as follows:

T& operator [](int idx) {
    return TheArray[idx];
}

T operator [](int idx) const {
    return TheArray[idx];
}

But I want to control the values ​​assigned arr[i] = value. I want to control the value between 0 and 9. Is there any syntax?

+6
source share
2 answers
Rene gave a good answer. In addition to this, here is a complete example. Please note that I have added "custom conversion", i.e. operator Tto class proxy_T.
#include <iostream>
#include <array>
#include <stdexcept>

template <class T>
class myClass
{
    std::array<T, 5> TheArray; // Some array...

    class proxy_T
    {
        T& value; // Reference to the element to be modified

    public:
        proxy_T(T& v) : value(v) {}

        proxy_T& operator=(T const& i)
        {
            if (i >= 0 and i <= 9)
            {
                value = i;
            }
            else
            {
                throw std::range_error(std::to_string(i));
            }
            return *this;
        }

        operator T() // This is required for getting a T value from a proxy_T, which make the cout-lines work
        {
            return value;
        }
    };

public:
    proxy_T operator [](int const idx)
    {
        return TheArray.at(idx);
    }

    T operator [](int const idx) const
    {
        return TheArray[idx];
    }
};

int main() {
    myClass<int> A;

    std::cout << A[0] << std::endl;
    A[0] = 2;
    std::cout << A[0] << std::endl;
    A[1] = 20;
}
+3
source

, ( T), , . [].

- :

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;
};
+6

Source: https://habr.com/ru/post/1016104/


All Articles