< cpp‎ | utility
Defined in header <source_location>
struct source_location;
(since C++20)

The source_location class represents certain information about the source code, such as file names, line numbers, and function names. Previously, functions that desire to obtain this information about the call site (for logging, testing, or debugging purposes) must use macros so that predefined macros like __LINE__ and __FILE__ are expanded in the context of the caller. The source_location class provides a better alternative.

source_­location meets the DefaultConstructible, CopyConstructible, CopyAssignable and Destructible requirements. Lvalue of source_location meets the Swappable requirement. Additionally, the following conditions are true:

It is intended that source_location has a small size and can be copied efficiently.


[edit] Member functions

constructs a new source_location with implementation-defined values
(public member function) [edit]
constructs a new source_location corresponding to the location of the call site
(public static member function) [edit]
Field access
return the line number represented by this object
(public member function) [edit]
return the column number represented by this object
(public member function) [edit]
return the file name represented by this object
(public member function) [edit]
return the name of the function represented by this object, if any
(public member function) [edit]

[edit] Example

#include <iostream>
#include <string_view>
#include <source_location>
void log(std::string_view message,
         const std::source_location& location = std::source_location::current())
    std::cout << "info:"
              << location.file_name() << ":"
              << location.line() << " "
              << message << '\n';
int main()
    log("Hello world!");

Possible output:

info:main.cpp:15 Hello world!