How to do some stuff with values assigned in subsc

2019-08-28 01:53发布

问题:

Suppose i've data array 0,0,1,1,2,2,5,5,7,7,2,2 as data member in class and i want to define subscript operator in such they

[i] returns me 2*i element of array but also i want let user to set elements, so

[i] = n, must be applied to both 2*i and 2*i+1.

Is it possible to do it with showing to user only subscript operator?

0,0,1,1,2,2,5,5,7,7,2,2
[3] = 4;
0,0,1,1,2,2,4,4,7,7,2,2

another workarounds? and in general it may be not only two elements.

回答1:

Indirectly, yes.

You can return a dedicated type with the subscript operator that works basically like a functor and takes care of assigning the value according to your specification:

struct AssignFunctor {
  MyArrayType& parent;
  size_t index;
  AssignFunctor(MyArrayType& parent, size_t index) : parent(parent), index(index) {}
  AssignFunctor& operator=(int k) {
    parent.set(index,k);
    parent.set(index*2,k);
  }
  operator int() const {
    return parent.get(index);
  }
};

struct MyArrayType {
  AssignFunctor operator[](size_t index) {
    return AssignFunctor(*this,index);
  }
  int operator[](size_t index) const {
    return get(index);
  }
  void set(size_t,int);
  int get(size_t) const;
};


回答2:

I am pretty sure you can implement it as mentioned above. But there's a ground rule for operator overloading. Don't change the meaning of the operator

In the user's perspective you're setting one element but that is applied to a different one as well. Better give meaningful function or change the design of your data structure.