C++ source_location

尉迟禄
2023-12-01
#include <iostream>
#include <string_view>
#include <source_location>

/*
	若想查看源代码对应的信息,之前都是使用log类,或宏__FILE__, __LINE__等,C++20中新增source_location类,可以更友好的展示文件名称、行号、列号、函数名称
*/
void log(const std::string_view message,
         const std::source_location location = 
               std::source_location::current())
{
    std::cout << "file: "
              << location.file_name() << "("
              << location.line() << ":"
              << location.column() << ") `"
              << location.function_name() << "`: "
              << message << '\n';
}
 
template <typename T> void fun(T x)
{
    log(x);
}
 
int main(int, char*[])
{
    log("Hello world!");
    fun("Hello C++20!");
}
 类似资料: