C++17三大核心新特性是std::optional、std::variant和std::filesystem,分别解决值存在性、类型多选一和跨平台文件操作问题;它们提升类型安全、表达力与开发效率。
Cpp17 带来了大量提升表达力、安全性与开发效率的语言和标准库更新。其中 std::optional、std::variant 和 std::filesystem 是最常用、也最值得优先掌握的三大新特性。它们分别解决了“值可能不存在”、“值可能是多种类型之一”、“跨平台文件操作难”这三个高频痛点。
它不是指针,也不是 pair
装“存在性”的类型。用它替代 -1、nullptr、npos 等魔数或空指针,能从类型系统上杜绝误用。
std::optional opt = 42; 或 std::optional empty = std::nullopt;
if (opt) { /* 有值 */ } 或 opt.has_value()
opt.value_or(-1)(无值时返回默认);*opt(需确保有值,否则未定义行为);opt.value()(无值时抛异常)struct Config { std::optional cache_size; }; )它是 C++ 版本的类型安全 union,同一时刻只持有一种给定类型(如 std::variant),编译器强制你处理所有可能分支,避免传统 union 的类型擦除风险。
std::variant v = "hello"; v = 100;
v.index() 返回索引(0 表示 int,1 表示 string);std::holds_alternative<:string>(v) 判断是否为某类型std::get<:string>(v)(类型错则抛异常);std::get_if(&v) (返回指针,空则为 nullptr)std::visit([](const auto& x) { /* 处理所有情况 */ }, v); —— 编译期全覆盖,不漏分支告别 platform-specific API(如 Windows 的 CreateFile 或 POSIX 的 stat)。头文件 提供路径抽象、遍历、元数据、复制/重命名等完整能力,开箱即用且线程安全。
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 项目在健壮性和可维护性上明显跃升一级。