Get the name of a std::function

hr0m picture hr0m · May 31, 2016 · Viewed 8k times · Source

In the following toy-example, I would like to get the name of a function. The function itself was given as an std::function argument. Is it possible in C++ to get name of a std::function object?

void printName(std::function<void()> func){
    //Need a function name()
    std::cout << func.name();
}

void magic(){};

//somewhere in the code
printName(magic());

output: magic

Otherwise I would have to give the function's name as a second parameter.

Answer

Bathsheba picture Bathsheba · May 31, 2016

No there isn't. Function names (like variable names) are compiled out so they are not visible at run-time.

Your best bet is to pass the name of the function (use a std::string or a const char*) as you've suggested yourself. (Alternatively you could base a solution on __func__ which was introduced in C++11.)