0

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.

2
  • 2
    Yes, it's possible (common implementation would be a proxy instance returned from operator[]). However, you might also simulate your array with a regular array and duplicate the members when they are read (what you should do depends on how you use this custom array). Commented Sep 3, 2012 at 14:18
  • @eq- thanks for idea about proxy!! Commented Sep 3, 2012 at 14:19

2 Answers 2

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; }; 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.