Is there a way to get the line number with out a macro in c++?

前端 未结 2 510
说谎
说谎 2021-01-28 05:16

I am writing a logger and I would like the logger to also record which line, function, and file called it. I have tried #define my_logger(format, ...) _log(format, __LINE_

2条回答
  •  猫巷女王i
    2021-01-28 05:52

    There cannot be such macro as __LINE_FUNCTION_WAS_CALLED_FROM__. There's no way it could work.

    Since C++20, there is a way to get the line, function, etc. into a normal function by passing default initialised std::source_location:

    void log(std::string_view message,
             std::source_location location = std::source_location::current());
    

    However, since it relies on a defaulted parameter, variadic arguments are a bit tricky to implement: How to use source_location in a variadic template function?

    Prior to C++20, a macro is your only portable option.


    I see that you call a function named _log in your macro. That identifier is reserved to the language implementation in the global namespace. You probably should give the function another name to avoid undefined behaviour.

    log is also reserved in the global namespace. You should declare all your names in a custom namespace anyway (except that custom namespace naturally).


    [the macro is] ... not the most portable

    If you were to replace __PRETTY_FUNCTION__ with __func__, then the macro would be portable to all standard conforming compilers - although the exact string given by __func__ may differ between implementations.

提交回复
热议问题