现代 C++ 必备知识:解锁 `std::optional`、`std::variant` 和 `std::any`

现代 C++ 标准(C++17)引入了多个实用工具类型, 例如 std::optional, std::variantstd::any, 它们各自解决了不同的编程问题. 理解这些工具的用途和适用场景有助于写出更高效, 更易维护的代码.


1. std::optional

  • std::optional<T> 表示一个可选值, 可以包含一个类型为 T 的值, 也可以为空.
  • 本质上, 它是一种类型安全的替代方案, 用于处理值可能缺失的情况.

用途

  • 避免使用裸指针或返回特殊值(如 nullptr 或错误码)来表示值的缺失.
  • 提供明确的语义, 表示某个值是可选的.

适用场景

1. 返回值可能为空的函数
#include <iostream>
#include <optional>
#include <vector>

std::optional<int> findIndex(const std::vector<int>& vec, int target) {
   
   
  for (size_t i = 0; i < vec.size(); ++i) {
   
   
    if (vec[i] == target) return i;
  }
  return std::nullopt;  // 返回空值
}

int main() {
   
   
  auto result = findIndex({
   
   1, 2, 3, 4}, 3);
  if (result) {
   
   
    std::cout << "Found at index: " << *result << std::endl;
  } else {
   
   
    std::cout << "Not found." << std::endl;
  }
  return 0;
}
2. 替代默认参数或特定标志值
std::optional<std::string> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

arong-xu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值