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.

2
  • 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__) Commented Nov 4, 2016 at 5: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: stackoverflow.com/questions/16100090/… Commented Nov 4, 2016 at 12:51

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.