Reputation: 31981
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?
Upvotes: 52
Views: 22607
Reputation: 111876
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.
Upvotes: 8
Reputation: 69855
I use a at() function, and have the operator[] call the at() function behind the scenes, so operator[] is just syntactic sugar. That's how std::vector does it, so it seems like a reasonable (with precedence) way to do it.
Now for a complete syntactic sugar hack (can't say I fully recommend it but might strike your fancy):
class Widget
{
Widget& self;
public:
Widget() :self(*this)
{}
void operator[](int)
{
printf("hello");
}
void test()
{
//scripting like sugar
//you pay the price of an extra reference per class though
self[1];
}
};
int main(int argc, char* argv[])
{
Widget w;
w[1];
w.test();
return 0;
}
Also if you want to do this for free, without paying the cost of the reference, AND are a follower of some evil sect dedicated to making programmers suffer you could do:
#define self (*this)
Actually I think that's how most handles are implemented in Apple's NS API...
Upvotes: 4
Reputation: 35188
An alternative to (*this)[bar]
is to use a named member function that does the work of operator[]
. Overloaded operators make things easier on your users. More importantly, they are part of your class' interface. Ask yourself if it really makes sense to implement your class in terms of its own public interface. If not, I suggest writing a separate (protected or private) member function to do the work, and then have operator[]
and any other function call it.
Upvotes: 3
Reputation: 29055
You could use (*this)[bar], but that might not be much of an improvement...
Upvotes: 1