std::source_location
來自 cppreference.com
在標頭檔案 <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) |