1

Is there a way to check inside a fnc what is this fnc name? I'm working currently on LargeInt class and I've realized that code for oparator> and operator< is almost identical so I would like to know what operator is calling me and react accordingly.
Thank you.

There is nothing we can do
  • 23,727
  • 30
  • 106
  • 194

5 Answers5

6

You can pass __func__ (C99) or __FUNCTION__ or __PRETTY_FUNCTION__ (non-standard).

There's no standard and reliable way to find the name of the caller of the function, if the caller doesn't provide the __func__ (imagine an inlined function with all symbols stripped).

But it's better to just refactor the common part into a standalone function if that bothers you.

int compare(const T& other) const { ... }

bool operator< (const T& other) const { return compare(other) < 0; }
bool operator> (const T& other) const { return compare(other) > 0; }
...
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
2

You seem really to be asking:

"Can I know which function called me?"

If so, no, there is no built in way of doing this, and it would IMHO be bad design to do this. You can however certainly implement the op< and op> (and the other relational operators) in terms of one another:

bool operator < ( A a1, A a2 ) {
    return a1.x < a2.x;     // base implementation
}

bool operator==( A a1, A a2 ) {
    return !(a1 < a2) && !(a2 < a1);
}

bool operator>( A a1, A a2 ) {
    return !(a1 == a2) && ! (a1 < a2 );
}

and so on.

1

In general, not without running inside an interactive debugger.

A compiled and linked C++ program doesn't necessarily include all the symbol information, so if you just broke somewhere in the stack and was able to trace the addresses of all the invoking functions you would have a hard time translating these addresses back to meaningful names. This is a big difference from, say, Java, where methods names can be reported by the program.

An interactive debugger, on the other hand, will be able to make the connection for you.

Uri
  • 88,451
  • 51
  • 221
  • 321
0

There is no standard or portable solution, but you might be interested in backtrace(), if you are developing on Linux.

Nevertheless, I think your comparison function should work the same regardless of who does it call.

jpalecek
  • 47,058
  • 7
  • 102
  • 144
0

Put the common code into a new method, and call it with an additional parameter distinguishing calls from the operator< and operator> methods.

bool LargeInt::almost_identical(LargeInt const &rhs, enum Caller caller)
{
    ...alleged almost identical code...
}

bool LargeInt::operator>(LargeInt const &rhs)
{
    return almost_identical(rhs, CALLER_GT);
}

bool LargeInt::operator<(LargeInt const &rhs)
{
    return almost_identical(rhs, CALLER_LT);
}
Matt Joiner
  • 112,946
  • 110
  • 377
  • 526