C++庫 - <source_location>



C++20中的<source_location>標頭檔案旨在捕獲執行時原始碼資訊。它提供關於程式碼位置的詳細資訊,例如檔名和行號,無需顯式傳遞這些資訊。這在除錯、日誌記錄和錯誤處理等場景中特別有用。

在引入<source_location>之前,檔名或行號是使用像`__FILE__`和`__LINE__`這樣的宏手動傳遞到日誌或錯誤處理程式中的。

包含<source_location>標頭檔案

要在C++程式中包含<source_location>標頭檔案,可以使用以下語法。

#include <source_location>

<source_location>標頭檔案的函式

以下是<source_location>標頭檔案中所有函式的列表。

序號 函式及描述
1 current

它構造一個對應於呼叫站點位置的新source_location。

2 line

它返回此物件表示的行號。

3 column

它返回此物件表示的列號。

4 file_name

它返回此物件表示的檔名。

5 function_name

它返回此物件表示的函式名。

獲取函式名

在下面的示例中,我們將呼叫source_location::current()並檢索函式名。

#include <iostream>
#include <source_location>
void x(const std::source_location & loc = std::source_location::current()) {
   std::cout << "Result : " << loc.function_name() << '\n';
}
void y() {
   x();
}
int main() {
   y();
}

輸出

以上程式碼的輸出如下:

Result : void y()

組合多個源位置

考慮下面的示例,我們將把列號和行號組合到一個日誌訊息中。

#include <iostream>
#include <source_location>
void a(const std::string & message,
   const std::source_location & location = std::source_location::current()) {
   std::cout << "Message: " << message << "\n";
   std::cout << "Line: " << location.line() << "\n";
   std::cout << "Column: " << location.column() << "\n";
}
int main() {
   a("WELCOME");
   return 0;
}

輸出

以下是以上程式碼的輸出:

Message: WELCOME
Line: 10
Column: 6
廣告