Reputation: 452
I'm working on a class that overloads the index operator ([]). To allow for assignment of an element, it's necessary for the operator to return a reference to the element. For example:
class myclass: public vector<int>
{
...
public:
int & myclass::operator [] (int i)
{
return vector<int>::operator[](i);
}
...
In this situation, the client code can use the returned reference to assign a value to an element. However, I would like to have a way to intercept the actual assignment of the element so I can use the assigned value to do some internal housekeeping. Is there a relatively clean and simple way to do this, or should I just create some accessor functions instead of using operator overloading?
Upvotes: 0
Views: 297
Reputation: 6046
AFAIK the std::vector index operator already returns reference to the item (either const or non-const), so no need to inherit and override.
If you want to intercept the assignment of the value, the correct way of doing this is to define/override the assignment operator of the value itself (you cannot do it in the vector index operator). That will of course not work with pure int, so you'd need to wrap the int in a class which will provide the assignment operator and there you can do "anything you want".
EDIT:
Ok I see, so then it might be needed to do some overrides. For the reverse lookup, one of the possibilities could be to not store the value in the reverse structure, but a pointer to it (to the original location). The value assignment in the original structure would then be reflected with the pointer redirection. This would also need to pass a custom comparison operator to the reverse lookup map, to not compare the pointers, but the values.
In general, it might be worth to also check boost::multi_index, which allows to do exactly that - create a single structure with multiple lookup indices.
Upvotes: 1
Reputation: 238491
There is no way to intercept the assignment of an integer. However, you could instead return a reference to a custom type whose assignment operator you have overloaded. The custom type can be convertible to int, so that it can be used as one.
Of course, this means that you cannot inherit std::vector<int>
which returns a reference to int
. You should avoid inheriting std::vector
publicly anyway. A user of your class may accidentally delete the object through a std::vector<int>*
which would have undefined behaviour.
Upvotes: 1