Home > Software design >  How to write a macro to convert member function to a string of its name?
How to write a macro to convert member function to a string of its name?

Time:10-24

I want to write

ProgressFunction.BindUFunction(this, NAMEOF(&MyActor::HandleProgress));

instead of

ProgressFunction.BindUFunction(this, "HandleProgress");

where BindUFunction's second parameter can only accept TCHAR*.

Question

How to define NAMEOF macro to convert &Whatever::FunctionName to "FunctionName"?

CodePudding user response:

You could stringify the argument and find the last : in it.

#include <cstring>
#include <iostream>
#define NAMEOF(x)   (strrchr(#x, ':') ? strrchr(#x, ':')   1 : #x)
int main() {
    std::cout << NAMEOF(&MyActor::HandleProgress);
}

This is very similar to https://stackoverflow.com/a/38237385/9072753 .

  • Related