跳至内容

std::optional、std::variant 和 std::expected

使用 C++17/23 和类型来表示可空值、类型安全的联合体和值或错误的返回──在编译时消除整类错误。

和类型:使无效状态不可表示

和类型在任何时候可以持有多种类型之一,编译器确保你处理所有可能性。C++17 引入了 std::optional 和 std::variant;C++23 添加了 std::expected。它们一起替代了容易出错的模式:

- std::optional 替代「返回 T 或哨兵值/空指针」
- std::variant 替代「union + 标签枚举」(类型安全,无未定义行为)
- std::expected 替代「返回 T 或设置错误码」

这些类型将错误检查从运行时纪律(期望程序员记得检查)转移到编译时强制(类型系统强制正确处理)。

std::optional──无需指针的可空值

std::optional 持有一个 T 值或空(std::nullopt)。它替代了使用特殊哨兵值(-1、""、nullptr)来表示「无值」的反模式。

optional_demo.cpp
#include <optional>
#include <string>
#include <map>
#include <iostream>

class UserDatabase {
public:
    void add(int id, const std::string& name) {
        users_[id] = name;
    }

    // Returns the user name, or std::nullopt if not found
    std::optional<std::string> find_user(int id) const {
        auto it = users_.find(id);
        if (it == users_.end()) {
            return std::nullopt;  // explicit "no value"
        }
        return it->second;  // implicit conversion to optional
    }

private:
    std::map<int, std::string> users_;
};

int main() {
    UserDatabase db;
    db.add(1, "Alice");
    db.add(2, "Bob");

    // Method 1: Check with has_value()
    auto result = db.find_user(3);
    if (result.has_value()) {
        std::cout << "Found: " << result.value() << '\n';
    } else {
        std::cout << "User not found\n";
    }

    // Method 2: value_or() with a default
    std::cout << db.find_user(1).value_or("<unknown>") << '\n';

    // Method 3: Boolean conversion (idiomatic)
    if (auto user = db.find_user(2)) {
        std::cout << "Found: " << *user << '\n';  // dereference like a pointer
    }
}

std::optional 的单子操作(C++23)

C++23 为 std::optional 添加了 and_then、transform 和 or_else,启用函数式链式操作而无需嵌套 if 语句。

monadic_optional.cpp
#include <optional>
#include <string>
#include <charconv>
#include <iostream>

// C++23 monadic operations on std::optional

std::optional<std::string> get_env(const std::string& name) {
    const char* val = std::getenv(name.c_str());
    if (!val) return std::nullopt;
    return std::string(val);
}

std::optional<int> parse_int(const std::string& s) {
    int value{};
    auto [ptr, ec] = std::from_chars(
        s.data(), s.data() + s.size(), value);
    if (ec != std::errc{}) return std::nullopt;
    return value;
}

std::optional<int> validated_port(int port) {
    if (port > 0 && port < 65536) return port;
    return std::nullopt;
}

int main() {
    // Without monadic ops: nested ifs
    // With monadic ops (C++23): clean pipeline
    int port = get_env("PORT")
        .and_then(parse_int)        // std::optional<int>
        .and_then(validated_port)   // std::optional<int>
        .or_else([]() -> std::optional<int> {
            std::cerr << "Using default port\n";
            return 8080;
        })
        .value();

    std::cout << "Port: " << port << '\n';
}

std::variant──类型安全的联合体

std::variant 在任何时候恰好持有其模板类型之一。与 C 联合体不同,它跟踪哪个类型是活动的,并防止访问错误的类型。使用 std::visit 配合访问者来处理所有替代方案。

variant_json.cpp
#include <variant>
#include <string>
#include <vector>
#include <iostream>
#include <cmath>

// A JSON-like value type using variant
struct JsonNull {};

using JsonValue = std::variant<
    JsonNull,                           // null
    bool,                               // true/false
    double,                             // number
    std::string,                        // string
    std::vector<struct JsonNode>        // array
>;

struct JsonNode {
    JsonValue value;
};

// Overloaded visitor pattern (C++17 trick)
template<class... Ts>
struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts>
overloaded(Ts...) -> overloaded<Ts...>;

std::string to_string(const JsonValue& val) {
    return std::visit(overloaded{
        [](JsonNull) -> std::string { return "null"; },
        [](bool b)   -> std::string { return b ? "true" : "false"; },
        [](double d) -> std::string { return std::to_string(d); },
        [](const std::string& s) -> std::string {
            return "\"" + s + "\"";
        },
        [](const std::vector<JsonNode>& arr) -> std::string {
            std::string result = "[";
            for (std::size_t i = 0; i < arr.size(); ++i) {
                if (i > 0) result += ", ";
                result += to_string(arr[i].value);
            }
            return result + "]";
        }
    }, val);
}

int main() {
    JsonValue v1 = 3.14;
    JsonValue v2 = std::string("hello");
    JsonValue v3 = JsonNull{};

    std::cout << to_string(v1) << '\n';  // 3.140000
    std::cout << to_string(v2) << '\n';  // "hello"
    std::cout << to_string(v3) << '\n';  // null

    // std::holds_alternative and std::get
    if (std::holds_alternative<double>(v1)) {
        std::cout << "v1 is double: " << std::get<double>(v1) << '\n';
    }

    // std::get throws std::bad_variant_access if wrong type
    // std::get_if returns nullptr instead — safer
    if (auto* ptr = std::get_if<std::string>(&v2)) {
        std::cout << "v2 is string: " << *ptr << '\n';
    }
}

std::expected──值或错误(C++23)

std::expected 持有类型 T 的值或类型 E 的错误。它是 C++ 对 Rust 的 Result 的回应。与异常不同,调用者必须显式处理错误。与错误码不同,错误可以携带丰富的信息。

expected_demo.cpp
#include <expected>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <system_error>

enum class ParseError {
    FileNotFound,
    InvalidFormat,
    ValueOutOfRange
};

std::string to_string(ParseError e) {
    switch (e) {
        case ParseError::FileNotFound:   return "file not found";
        case ParseError::InvalidFormat:  return "invalid format";
        case ParseError::ValueOutOfRange: return "value out of range";
    }
    return "unknown";
}

std::expected<std::string, ParseError> read_file(const std::string& path) {
    std::ifstream file(path);
    if (!file.is_open()) {
        return std::unexpected(ParseError::FileNotFound);
    }
    std::ostringstream ss;
    ss << file.rdbuf();
    return ss.str();  // implicitly wraps in expected
}

std::expected<int, ParseError> parse_port(const std::string& content) {
    try {
        int port = std::stoi(content);
        if (port < 1 || port > 65535) {
            return std::unexpected(ParseError::ValueOutOfRange);
        }
        return port;
    } catch (...) {
        return std::unexpected(ParseError::InvalidFormat);
    }
}

int main() {
    // Monadic chaining (C++23)
    auto result = read_file("port.conf")
        .and_then(parse_port)
        .or_else([](ParseError e) -> std::expected<int, ParseError> {
            std::cerr << "Error: " << to_string(e)
                      << ", using default\n";
            return 8080;  // fallback
        });

    std::cout << "Port: " << result.value() << '\n';
}
常见陷阱

这些类型功能强大,但如果使用不当会有锐利的边缘。

  • 对空的 std::optional 调用 .value() 会抛出 std::bad_optional_access──始终先检查或使用 value_or()
  • 对错误类型使用 std::get(variant) 会抛出 std::bad_variant_access──优先使用 std::visit 或 std::get_if
  • std::variant 中有重复类型(例如 variant)是有效的但令人困惑──只能使用基于索引的访问
  • 忽略 std::expected 中的错误而总是调用 .value() 会失去其目的──检查 .has_value() 或使用单子操作
  • std::optional 在标准中不存在(尚未)──使用 std::optional> 作为替代方案
最佳实践

为每种情况选择正确的和类型。

  • std::optional:可能不存在的值──查找、可选参数、延迟初始化
  • std::variant:可能是多种类型之一的值──AST 节点、JSON 值、消息类型
  • std::expected:可能失败的计算──文件 I/O、解析、验证,任何返回 T 或错误的操作
关键要点
  • std::optional 用类型安全的「值或无」替代哨兵值和空指针
  • std::variant 用类型安全的标签联合体替代 C 联合体──使用 std::visit 进行穷举处理
  • std::expected(C++23)是 C++ 的 Result──值或错误,带单子链式操作
  • C++23 单子操作(and_then、transform、or_else)启用干净的管道式处理,无需嵌套 if 块
  • 和类型将错误检查从运行时纪律转移到编译时强制

测验 — 检验你的知识

(20 经验值)

1. `std::optional::value_or(default)` 做什么?

2. 使用 `std::variant` 时,`std::visit` 比 `std::get<T>` 有什么优势?

3. `std::expected<T, E>` 与简单地抛出异常有何不同?