✨beginner
std::source_location
Get source code location information
Example Code
cpp
#include <source_location>#include <iostream>#include <string_view>// Logging with automatic locationvoid log(std::string_view message, const std::source_location& loc = std::source_location::current()) { std::cout << loc.file_name() << ":" << loc.line() << " [" << loc.function_name() << "] " << message << std::endl;}// Assert with location infovoid my_assert(bool condition, std::string_view msg, const std::source_location& loc = std::source_location::current()) { if (!condition) { std::cerr << "Assertion failed: " << msg << "\n" << " at " << loc.file_name() << ":" << loc.line() << "\n" << " in " << loc.function_name() << std::endl; }}void do_something() { log("Processing started"); // ... work ... log("Processing complete");}int main() { log("Application starting"); do_something(); int value = 42; my_assert(value > 0, "value must be positive"); my_assert(value < 10, "value must be less than 10"); // Fails return 0;}/* Output:main.cpp:30 [main] Application startingmain.cpp:17 [do_something] Processing startedmain.cpp:19 [do_something] Processing completeAssertion failed: value must be less than 10 at main.cpp:35 in main*/Explanation
std::source_location provides information about the source code location where it's used. It replaces the need for __FILE__, __LINE__, and __func__ macros with a type-safe alternative.
Key Points
- 1file_name() - source file path
- 2line() - line number
- 3function_name() - enclosing function
- 4Use as default parameter for call-site info