C++ 庫 - <expected>



C++ 中的<expected> 標頭檔案提供了各種函式和操作,用於以能夠表達預期值的存在或意外錯誤的方式處理值或錯誤。

它類似於 std::optional,但此外,還能夠儲存在預期值不存在時資訊。此 <expected> 標頭檔案是通用實用程式庫的一部分。

包含 <expected> 標頭檔案

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

#include <expected>

<expected> 標頭檔案的函式

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

序號 函式及描述
1 operator->, operator*

這些函式提供對預期值的訪問。

2 operator bool, has_value

這些函式檢查物件是否包含預期值。

3 value

此函式返回預期值。

4 error

此函式返回意外值。

5 value_or

如果存在,此函式返回預期值;否則,返回另一個值。

6 error_or

如果存在,此函式返回意外值;否則,返回另一個值。

檢索值

在以下示例中,我們將使用 value() 在存在的情況下檢索預期值。

#include <iostream>
#include <expected>
int main() {
    std::expected<int, std::string> result = 42;  
    if (result.has_value()) {
        std::cout << "Expected value: " << result.value() << std::endl;  
    } else {
        std::cout << "Unexpected error: " << result.error() << std::endl;
    }
    return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

Expected value: 42

單子操作

單子操作提供了一種操作和轉換預期物件中值或錯誤的方法。

序號 函式及描述
1 and_then

如果存在,此函式返回給定函式對預期值的返回值;否則,返回預期本身。

2 transform

如果存在,此函式返回包含已轉換預期值的預期;否則,返回預期本身。

3 or_else

如果預期物件包含預期值,此函式返回預期本身;否則,返回給定函式對意外值的返回值。

4 transform_error

如果預期物件包含預期值,此函式返回預期本身;否則,返回包含已轉換意外值的預期。

單子操作示例

在以下示例中,我們將使用 and_then() 函式將 multiply_by_two 應用於預期值 (21),返回一個包含結果 (42) 的新 std::expected 物件。

#include <iostream>
#include <expected>
std::expected<int, std::string multiply_by_two(int x) {
    return x * 2;
}
int main() {
    std::expected<int, std::string> result = 21;
    auto new_result = result.and_then(multiply_by_two);  

    if (new_result.has_value()) {
        std::cout << "New expected value: " << new_result.value() << std::endl;
    } else {
        std::cout << "Unexpected error: " << new_result.error() << std::endl;
    }
    return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

New expected value: 42

修飾符

std::expected 中的修飾符是允許我們修改預期物件的狀態或內容的函式。

序號 函式及描述
1 emplace

此函式就地構造預期值,替換任何現有的值或錯誤。

2 operator bool, has_value

此函式交換兩個物件的內容。

修改值

在以下示例中,我們將使用 emplace(),它將任何當前狀態(無論它包含值還是錯誤)替換為新的預期值 (10)。

#include <iostream>
#include <expected>
int main() {
    std::expected<int, std::string> result = std::unexpected("Initial error");
    result.emplace(10);

    if (result.has_value()) {
        std::cout << "Replaced with new expected value: " << result.value() << std::endl;
    } else {
        std::cout << "Unexpected error: " << result.error() << std::endl;
    }
    return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

Replaced with new expected value: 10
廣告