Scroll to navigation

std::source_location(3) C++ Standard Libary std::source_location(3)


std::source_location - std::source_location


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

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

* std::is_nothrow_move_constructible_v<std::source_location>,
* std::is_nothrow_move_assignable_v<std::source_location>, and
* std::is_nothrow_swappable_v<std::source_location>.

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

It is unspecified whether the copy/move constructors and the copy/move assignment
operators of source_location are trivial and/or constexpr.

Member functions

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


Feature-test macro: __cpp_lib_source_location


// Run this code

#include <iostream>
#include <string_view>
#include <source_location>

void log(const std::string_view message,
const std::source_location location =
std::cout << "file: "
<< location.file_name() << "("
<< location.line() << ":"
<< location.column() << ") `"
<< location.function_name() << "`: "
<< message << '\n';

template <typename T> void fun(T x)

int main(int, char*[])
log("Hello world!");
fun("Hello C++20!");

Possible output:

file: main.cpp(23:8) `int main(int, char**)`: Hello world!
file: main.cpp(18:8) `void fun(T) [with T = const char*]`: Hello C++20!

See also

stacktrace_entry representation of an evaluation in a stacktrace
(C++23) (class)
Filename and line information