现代 C++ 标准(C++17)引入了多个实用工具类型, 例如 std::optional, std::variant 和 std::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>

2001

被折叠的 条评论
为什么被折叠?



