Search code examples
c++unreal-engine5

How to write a macro to convert member function to a string of its name?


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"?


Solution

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