Is there a way to get function name inside a C++ function?

后端 未结 4 921
后悔当初
后悔当初 2020-12-01 06:22

I want to implement a function tracer, which would trace how much time a function is taking to execute. I have following class for the same:-

class FuncTrace         


        
4条回答
  •  情深已故
    2020-12-01 06:57

    C++20 std::source_location::function_name

    This does basically exactly what you want.

    https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:

    #include 
    #include 
    #include 
    
    void log(std::string_view message,
             const std::source_location& location std::source_location::current()
    ) {
        std::cout << "info:"
                  << location.file_name() << ":"
                  << location.line() << ":"
                  << location.function_name() << " "
                  << message << '\n';
    }
    
    int main() {
        log("Hello world!");
    }
    

    Possible output:

    info:main.cpp:16:main Hello world!
    

    so note how the call preserves caller information.

    I have covered the relevant standards in a bit more detail at: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

提交回复
热议问题