C++17:实用标准
探索 C++17 最具影响力的特性:结构化绑定、std::optional/variant/any、std::string_view、std::filesystem、if constexpr 以及新属性。
为什么 C++17 重要
C++17 常被称为「实用标准」,因为它引入了大量简化日常编码的特性,而无需深入的模板元编程知识。它移除了遗留包袱(如 std::auto_ptr 和三字符组)、添加了词汇类型(std::optional、std::variant、std::any),并引入了使代码更简短、更清晰的语法糖。如果你今天正在编写生产环境的 C++ 代码,C++17 应该是你的最低基准。
结构化绑定与初始化语句
结构化绑定允许你将聚合体(结构体、数组、pair、tuple)解包为单个声明中的命名变量。结合 if/switch 初始化器,它们消除了许多临时变量:
#include <iostream>
#include <map>
#include <string>
#include <tuple>
std::tuple<std::string, int, double> get_employee() {
return {"Alice", 42, 95000.0};
}
int main() {
// Structured binding with tuple
auto [name, age, salary] = get_employee();
std::cout << name << " is " << age << " years old\n";
// Structured binding with map iteration
std::map<std::string, int> scores{{"Alice", 95}, {"Bob", 87}};
for (const auto& [student, score] : scores) {
std::cout << student << ": " << score << "\n";
}
// if with initializer — the variable is scoped to the if/else
if (auto it = scores.find("Alice"); it != scores.end()) {
std::cout << "Found: " << it->second << "\n";
} else {
std::cout << "Not found\n";
}
// 'it' no longer exists here — no scope leakage
// Structured binding with array
int arr[3] = {10, 20, 30};
auto [x, y, z] = arr;
std::cout << x << ", " << y << ", " << z << "\n";
return 0;
}词汇类型:optional、variant、any
std::optional 表示一个可能存在也可能不存在的值(替代哨兵值和输出参数)。std::variant 是类型安全的联合体。std::any 持有任何可拷贝的类型并进行运行时类型检查:
#include <iostream>
#include <optional>
#include <variant>
#include <any>
#include <string>
// optional: replaces "return -1 on failure" patterns
std::optional<int> find_index(const std::string& haystack, char needle) {
for (size_t i = 0; i < haystack.size(); ++i) {
if (haystack[i] == needle) return static_cast<int>(i);
}
return std::nullopt; // no value
}
int main() {
// std::optional
auto idx = find_index("hello", 'l');
if (idx.has_value()) {
std::cout << "Found at index " << *idx << "\n"; // 2
}
std::cout << idx.value_or(-1) << "\n"; // safe default
// std::variant — type-safe union
std::variant<int, double, std::string> value = "hello";
std::cout << std::get<std::string>(value) << "\n";
// Visit pattern — exhaustive handling of all types
std::visit([](const auto& v) {
std::cout << "Value: " << v << "\n";
}, value);
value = 3.14; // now holds a double
std::cout << std::get<double>(value) << "\n";
// std::any — truly any type, with runtime checking
std::any data = 42;
std::cout << std::any_cast<int>(data) << "\n";
data = std::string("world");
std::cout << std::any_cast<std::string>(data) << "\n";
return 0;
}string_view 与 filesystem
std::string_view 是一个轻量级的、非拥有的字符串引用。当你只需要读取字符串时,它避免了拷贝。std::filesystem 提供了跨平台的可移植路径操作和文件操作:
#include <iostream>
#include <string>
#include <string_view>
#include <filesystem>
namespace fs = std::filesystem;
// string_view avoids copying — just a pointer + length
void print_trimmed(std::string_view sv) {
auto start = sv.find_first_not_of(' ');
auto end = sv.find_last_not_of(' ');
if (start != std::string_view::npos) {
std::cout << sv.substr(start, end - start + 1) << "\n";
}
}
int main() {
std::string name = " Hello, C++17! ";
print_trimmed(name); // no copy — string_view binds to string
print_trimmed(" world "); // no copy — binds to string literal
// std::filesystem — portable path operations
fs::path source_dir = "/home/user/project/src";
std::cout << "Filename: " << source_dir.filename() << "\n";
std::cout << "Parent: " << source_dir.parent_path() << "\n";
std::cout << "Exists: " << fs::exists(source_dir) << "\n";
// Iterate directory entries
for (const auto& entry : fs::directory_iterator(".")) {
if (entry.is_regular_file()) {
std::cout << entry.path().filename()
<< " (" << entry.file_size() << " bytes)\n";
}
}
// Create directories recursively
fs::create_directories("output/logs/2024");
return 0;
}if constexpr、CTAD 及更多
if constexpr 在模板内启用编译时分支 ── 不匹配的分支会被完全丢弃。类模板参数推导(CTAD)允许你在编译器能推导出模板参数时省略它们。折叠表达式简化了可变参数模板参数包:
#include <iostream>
#include <string>
#include <vector>
#include <type_traits>
// if constexpr — branches resolved at compile time
template<typename T>
std::string to_string_safe(T value) {
if constexpr (std::is_arithmetic_v<T>) {
return std::to_string(value);
} else if constexpr (std::is_same_v<T, std::string>) {
return value;
} else {
return "[unsupported type]";
}
}
// Fold expressions — collapse parameter packs
template<typename... Args>
auto sum(Args... args) {
return (args + ...); // unary right fold
}
template<typename... Args>
void print_all(Args&&... args) {
((std::cout << args << " "), ...); // fold over comma
std::cout << "\n";
}
int main() {
std::cout << to_string_safe(42) << "\n";
std::cout << to_string_safe(std::string("hi")) << "\n";
std::cout << sum(1, 2, 3, 4, 5) << "\n"; // 15
print_all(1, "hello", 3.14); // 1 hello 3.14
// CTAD — no need for std::vector<int>
std::vector v{1, 2, 3, 4, 5}; // deduced as vector<int>
std::pair p{"hello", 42}; // deduced as pair<const char*, int>
// Nested namespaces
// namespace A::B::C { } instead of namespace A { namespace B { namespace C { } } }
// Inline variables — can be defined in headers without ODR violations
// inline constexpr int version = 17;
return 0;
}C++17 标准化了三个重要属性:
[[nodiscard]] ── 如果返回值被丢弃则发出警告。用于返回值应始终被检查的函数(错误码、已分配的资源、工厂函数)。
[[maybe_unused]] ── 抑制未使用变量/参数的警告。适用于仅在调试构建或特定平台代码中使用的变量。
[[fallthrough]] ── 表示 switch case 中的故意贯穿,消除编译器警告。
在你的 API 上积极采用 [[nodiscard]]。被丢弃的错误码是一个等待发生的 bug。
绝对不要返回引用局部字符串的 std::string_view。由于 string_view 不拥有其数据,底层字符串可能在视图被使用之前就被销毁,导致未定义行为:
// DANGEROUS — returns a view to a destroyed temporary!
std::string_view bad() {
std::string s = "hello";
return s; // s is destroyed at end of function!
}经验法则:将 string_view 用于参数(读取数据),将 std::string 用于返回值(拥有数据)。
- 结构化绑定(
auto [a, b] = ...)可以简洁地解包 tuple、pair、结构体和数组 std::optional替代哨兵值;std::variant替代不安全的联合体;std::any用于真正的动态类型std::string_view避免只读字符串访问时的拷贝 ── 但要注意悬空引用if constexpr在模板中启用编译时分支,消除 SFINAE 样板代码- CTAD 让编译器推导模板参数:
std::vector v{1,2,3}直接可用 - 在返回值不应被忽略的函数上使用
[[nodiscard]]
测验 — 检验你的知识
(15 经验值)1. 在 C++17 中 `auto [x, y] = std::make_pair(1, 2.0);` 做了什么?
2. `std::optional<int>` 表示什么?
3. 为什么从函数返回引用局部字符串的 `std::string_view` 是危险的?