c++17三大核心新特性是std::optional、std::variant和std::Filesystem,分别解决值存在性、类型多选一和跨平台文件操作问题;它们提升类型安全、表达力与开发效率。

Cpp17 带来了大量提升表达力、安全性与开发效率的语言和标准库更新。其中 std::optional、std::variant 和 std::filesystem 是最常用、也最值得优先掌握的三大新特性。它们分别解决了“值可能不存在”、“值可能是多种类型之一”、“跨平台文件操作难”这三个高频痛点。
std::optional:安全表达“可能没有值”
它不是指针,也不是 pair
- 构造简单:
std::optional<int> opt = 42;</int>或std::optional<int> empty = std::nullopt;</int> - 检查是否存在:
if (opt) { /* 有值 */ }或opt.has_value() - 安全取值:
opt.value_or(-1)(无值时返回默认);*opt(需确保有值,否则未定义行为);opt.value()(无值时抛异常) - 典型场景:函数返回可能失败的结果(如配置解析、查找、转换),结构体中可选字段(如
Struct Config { std::optional<size_t> cache_size; };</size_t>)
std::variant:类型安全的“多选一”容器
它是 C++ 版本的类型安全 union,同一时刻只持有一种给定类型(如 std::variant<int std::String double></int>),编译器强制你处理所有可能分支,避免传统 union 的类型擦除风险。
- 赋值自然:
std::variant<int std::string> v = "hello"; v = 100;</int> - 查询当前类型:
v.index()返回索引(0 表示 int,1 表示 string);std::holds_alternative<:string>(v)</:string>判断是否为某类型 - 安全访问:
std::get<:string>(v)</:string>(类型错则抛异常);std::get_if<int>(&v)</int>(返回指针,空则为 nullptr) - 推荐用法:
std::visit([](const auto& x) { /* 处理所有情况 */ }, v);—— 编译期全覆盖,不漏分支
std::filesystem:统一、现代的文件系统操作
告别 platform-specific API(如 windows 的 CreateFile 或 POSIX 的 stat)。头文件 <filesystem></filesystem> 提供路径抽象、遍历、元数据、复制/重命名等完整能力,开箱即用且线程安全。
立即学习“C++免费学习笔记(深入)”;
- 路径操作:
std::filesystem::path p = "logs/Error.txt"; p.parent_path(); p.extension(); - 判断与查询:
exists(p)、is_regular_file(p)、file_size(p)、last_write_time(p) - 遍历目录:
for (const auto& entry : std::filesystem::directory_iterator("data")) { ... } - 常用动作:
create_directories(p.parent_path())、copy_file(src, dst)、rename(old_p, new_p)
基本上就这些。optional 解决“有没有”,variant 解决“是哪个”,filesystem 解决“在哪”。三者配合使用,能让 C++17 项目在健壮性和可维护性上明显跃升一级。