std::source_location
来自 cppreference.cn
在头文件 <source_location> 中定义 |
||
struct source_location; |
(C++20 起) | |
std::source_location
类表示有关源代码的特定信息,例如文件名、行号和函数名。以前,需要获取有关调用站点此信息(用于日志记录、测试或调试目的)的函数必须使用宏,以便在调用方的上下文中展开像 __LINE__ 和 __FILE__ 这样的预定义宏。std::source_location
类提供了一个更好的替代方案。
std::source_location
满足 DefaultConstructible、CopyConstructible、CopyAssignable、Destructible 和 Swappable 的要求。
此外,以下条件为 true
- std::is_nothrow_move_constructible_v<std::source_location>,
- std::is_nothrow_move_assignable_v<std::source_location>,以及
- std::is_nothrow_swappable_v<std::source_location>.
std::source_location
的设计目标是具有小尺寸并能高效复制。
std::source_location
的复制/移动构造函数和复制/移动赋值运算符是否是平凡的(trivial)和/或 constexpr 是未指定的。
目录 |
[编辑] 成员函数
创建 | |
使用实现定义的值构造新的 source_location (public member function) | |
[静态] |
构造对应于调用站点位置的新 source_location (public static member function) |
字段访问 | |
返回此对象表示的行号 (public member function) | |
返回此对象表示的列号 (public member function) | |
返回此对象表示的文件名 (public member function) | |
返回此对象表示的函数名(如果有) (public member function) |
[编辑] 注意
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__cpp_lib_source_location |
201907L |
(C++20) | 源代码信息捕获 (std::source_location ) |
[编辑] 示例
运行此代码
#include <iostream> #include <source_location> #include <string_view> void log(const std::string_view message, const std::source_location location = std::source_location::current()) { std::clog << "file: " << location.file_name() << '(' << location.line() << ':' << location.column() << ") `" << location.function_name() << "`: " << message << '\n'; } template<typename T> void fun(T x) { log(x); // line 20 } int main(int, char*[]) { log("Hello world!"); // line 25 fun("Hello C++20!"); }
可能的输出
file: main.cpp(25:8) `int main(int, char**)`: Hello world! file: main.cpp(20:8) `void fun(T) [with T = const char*]`: Hello C++20!
[编辑] 参阅
更改源代码的行号,并可选地更改当前文件名 (preprocessing directive) | |
(C++23) |
栈追踪中一次求值的表示 (class) |