Examples of Source Location
Example 1: Program to illustrate the use of std::source_location
C++
// C++ Program to demonstrate use of source_loaction to // print function details #include <iostream> #include <source_location> using namespace std; // function for which we check source location void foo() { // declaring source location object for current source source_location src = source_location::current(); // printing details cout << "Function: " << src.function_name() << '/n' ; cout << "File: " << src.file_name() << "\n" ; cout << "Line: " << src.line() << "\n" ; cout << "Column: " << src.column() << "\n" ; } // driver code int main() { foo(); return 0; } |
Output
Function: void foo() File: main.cpp Line: 11 Column: 51
Example 2: Program to illustrate the use of source location for log messages.
C++
// C++ program to log messages with source location using // source_location header #include <iostream> #include <source_location> void log (std::string_view message, const std::source_location& location = std::source_location::current()) { std::cout << location.file_name() << ":" << location.line() << " (" << location.function_name() << "): " << message << "\n" ; } void foo() { log ( "Hello, world!" ); } int main() { foo(); return 0; } |
Output
main.cpp:9 (void foo()) Hello, world!
std::source_location in C++ 20
The latest C++ standard version 20, brought about a fresh header file called <source_location> Header. It has an efficient method of obtaining details of a function or expression’s source location while running. This functionality is immensely beneficial for debugging and profiling activities that help developers locate errors and performance problems more quickly.