Namespaces
Variants

std::source_location

来自 zh.cppreference.net
 
 
 
 
定义于头文件 <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 的复制/移动构造函数以及复制/移动赋值运算符是否为平凡的和/或 constexpr。

成员函数

创建
构造具有实现定义值的 source_location 对象
(公开成员函数)
[static]
构造对应于调用点位置的新 source_location 对象
(公开静态成员函数)
字段访问
返回此对象表示的行号
(公开成员函数)
返回此对象表示的列号
(公开成员函数)
返回此对象表示的文件名
(公开成员函数)
返回此对象表示的函数名称(如果存在)
(公开成员函数)

注释

功能测试 宏 值 标准 功能
__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); // 第20行
}
int main(int, char*[])
{
    log("Hello world!"); // 第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!

参阅

更改源代码的行号,并可选地更改当前文件名
(预处理指令)
栈回溯中一次求值的表示
(类)