0

In C++, is there a way to override the array subscript using a macro? For example, I would like to use something like this:

#define operator[](index) GetAt(index, __FUNCTION__)

Using this macro, whenever I use an array subscript, I would be able to know the name of the calling method.

For example:

class A
{
....
    int myArray[10];
    int& operator[](int index)
    {
        return myArray[index];
    }
    int& GetAt(index, const char * caller)
    {
        printf("Called by %s", caller);
        return myArray[index];
    }
....
}

class B
{
    void doSomething()
    {
        A obj = new A();
        int val = obj[1]; //<- this will call GetAt(..) and printf the caller's name.
    }
}
#define operator[](index) GetAt(index, __FUNCTION__)

Obviously the #define does not work, but I'm looking to do something similar.

Simon Senécal
  • 111
  • 2
  • 6
  • 3
    What's your use case, what do you actually want to achieve? Sounds like a XY-problem. Remeber that `#define` does plain text replacement, so `operator` would be rendered as `[](index) GetAt(index, __FUNCTION__)` – πάντα ῥεῖ Nov 04 '16 at 05:27
  • I'm trying to find the calling method name when I access an array element. I wanted to use a macro like in this post: http://stackoverflow.com/questions/16100090/how-can-we-know-the-caller-functions-name – Simon Senécal Nov 04 '16 at 12:51

0 Answers0