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

Solution 1:

(*this)[bar];

works fine for me.

Solution 2:

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.

Solution 3:

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...