Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
c++20
source
location
communitycreator

What is the std::source_location in C++?

Danil

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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_location header file.

Built-in functions

std::source_location comes with some basic built-in functions. They are explained below.

Creation

  • 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.

Field access

  • 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.

Example

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!");
}

Output

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!

RELATED TAGS

c++
c++20
source
location
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring