Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading Square Brackets Operator to Accept Value

I'm writing a collection class. I want to overload the square brackets operator ([]) to provide access to elements in the collection.

int operator[](int i)
{
    // Do stuff here
}

My problem is that I don't see how to write this so that I could use this operator to accept a value:

myClassInstance[0] = value;

I see no way to declare the square brackets operator with an additional argument (the value to assign to the element).

I know I can simply return int& and the caller can assign a value to that, but internally each element is stored in a different format than the one made public.

Is this even possible?

like image 363
Jonathan Wood Avatar asked Jan 01 '11 03:01

Jonathan Wood


2 Answers

Write an int_proxy class that is implicitly convertible to int and is assignable from int. You'll need at least two member functions:

operator int();
int_proxy& operator=(int);

In this proxy class, store whatever information you need to be able to retrieve and set the value in the container. Do the retrieval in the conversion operator and the assignment in the assignment operator.

like image 125
James McNellis Avatar answered Sep 23 '22 16:09

James McNellis


Return a reference to an object that has an operator = that can stuff the int where it needs to go. Look at the boolean vector trickery in STL for an example, if not necessarily a wonderfully exemplary example.

like image 40
bmargulies Avatar answered Sep 22 '22 16:09

bmargulies