C++20 的 std::source_location
为了处理上述封装为函数出现的问题,C++20 推出了 std::source_location
基本使用
std::source_location 的内容非常简单,只有 6 个相关函数:
- 默认构造函数
- 静态 current() 用于构造对应调用点的新对象
- line() 返回此对象所表示的行号
- column() 返回此对象所表示的列号
- file_name() 返回此对象所表示的文件名
- function_name() 返回此对象表示的函数名
若它存在使用方式也非常简单,由于是和调用点有关,所以不用担心上面使用 __LINE__ 的问题。
代码和使用效果如下:
#include <iostream> #include <source_location> #include <string> bool log(const std::string& msg = "" , const std::source_location location = std::source_location::current() ) { std::cout << "File: " << location.file_name() << std::endl; std::cout << "Fun: " << location.function_name() << std::endl; std::cout << "Line: " << location.line() << std::endl; std::cout << "Column: " << location.column() << std::endl; std::cout << "Msg: " << msg << std::endl; return true; } const bool flag = log(); int main() { log("Hello world!"); }