Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Convenient way to access operator[] from within class?

I have a C++ class that overloads operator[], the array subscript/brackets operator. This is awfully convenient outside of my class, where I can write foo[bar]. However, I can't figure out how to use this notation when I'm implementing methods inside my class.

I know I can write operator[](bar) or this->operator[](bar) but those are fairly unwieldy and take away a lot of the convenience of the operator in the first place. (I also know I can just add a new method that calls the operator.) Is there a way I can write this[bar] or this->[bar] or something similarly nice?

like image 621
A. Rex Avatar asked Mar 03 '09 03:03

A. Rex


2 Answers

(*this)[bar]; 

works fine for me.

like image 154
Evan Teran Avatar answered Oct 10 '22 13:10

Evan Teran


Use

(*this)[bar] 

to call the operator[] of the instance object.

Assuming bar is an integer (or can be auto-converted to one), this[bar] treats the this pointer as an array and indexes the bar-th element of that array. Unless this is in an array, this will result in undefined behavior. If bar isn't integer-like, expect a compile-time error.

like image 29
Mr Fooz Avatar answered Oct 10 '22 15:10

Mr Fooz