std::source_location is a class first introduced in C++20 that represents certain information about the source code, such as file names, line numbers, and function names.
Make sure to include the
source_locationheader file.
std::source_location comes with some basic built-in functions. They are explained below.
source_location(): Construct a new object of unspecified value.source_location::current(): Static member function, construct a new object that corresponds to the location of the call site.line(): Return the line number represented by the object.column(): Return the column number represented by the object.file_name(): Return the file name represented by the object.function_name(): Return the name of the function represented by the object, if any.The following example uses the functions described below. It implements the log function, which outputs information about the place where it was called.
#include <source_location>#include <iostream>void log(const char* 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() {log("Hello world!");fun("Hello C++20!");}
file: main.cpp(24:8) `int main(int, char**)`: Hello world!
file: main.cpp(19:8) `void fun(T) [with T = const char*]`: Hello C++20!