C++17 是 C++ 编程语言的一个重要版本,引入了许多新特性和改进,使得代码更加简洁、高效和安全。本文将详细介绍 C++17 的主要新特性,并提供相应的代码示例。
一、C++17 新特性概述
C++17 引入了许多新特性,主要包括:
- 结构化绑定(Structured Bindings)
- if 和 switch 中的初始化语句
- 内联变量(Inline Variables)
- 折叠表达式(Fold Expressions)
-
std::optional
和std::variant
-
std::string_view
- 并行算法(Parallel Algorithms)
- 文件系统库(Filesystem Library)
- 其他改进和优化
二、结构化绑定(Structured Bindings)
结构化绑定允许你将一个复合类型(如 std::pair
、std::tuple
或数组)的成员绑定到多个变量上。
示例代码
#include <iostream>
#include <tuple>
int main() {
// 使用 std::tuple
std::tuple<int, double, std::string> t = {1, 3.14, "Hello"};
auto [id, pi, message] = t;
std::cout << "ID: " << id << ", Pi: " << pi << ", Message: " << message << std::endl;
// 使用数组
int arr[3] = {10, 20, 30};
auto [a, b, c] = arr;
std::cout << "Array elements: "<< a << ", "<< b << ", "<< c << std::endl;
return 0;
}
三、if 和 switch 中的初始化语句
在 C++17 中,你可以在 if
和 switch
语句中进行变量声明和初始化。
示例代码
#include <iostream>
#include <optional>
std::optional<int> findValue(const std::vector<int>& vec, int target) {
for (int val : vec) {
if (val == target) {
return val;
}
}
return std::nullopt;
}
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// if 中的初始化语句
if (auto value = findValue(numbers, 3); value.has_value()) {
std::cout << "Found: " << *value << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
// switch 中的初始化语句(C++17 不支持直接在 switch 中初始化,但可以通过作用域实现)
{
auto value = findValue(numbers, 6);
switch (value.has_value()) {
case true:
std::cout << "Found: " << *value << std::endl;
break;
case false:
std::cout << "Not found" << std::endl;
break;
}
}
return 0;
}
四、内联变量(Inline Variables)
内联变量允许你在头文件中定义变量,而不会导致多重定义错误。
示例代码
// my_header.h
#ifndef MY_HEADER_H
#define MY_HEADER_H
#include <string>
inline const std::string appName = "MyApp";
#endif // MY_HEADER_H
// main.cpp
#include <iostream>
#include "my_header.h"
int main() {
std::cout << "Application Name: " << appName << std::endl;
return 0;
}
五、折叠表达式(Fold Expressions)
折叠表达式简化了可变参数模板的展开操作。
示例代码
#include <iostream>
template<typename... Args>
auto sum(Args... args) {
return (args + ...); // 折叠表达式
}
int main() {
std::cout << "Sum of 1, 2, 3, 4, 5: " << sum(1, 2, 3, 4, 5) << std::endl;
return 0;
}
六、std::optional
和 std::variant
1. std::optional
std::optional
用于表示一个可能包含值或不包含值的对象。
#include <iostream>
#include <optional>
std::optional<int> divide(int a, int b) {
if (b == 0) {
return std::nullopt;
}
return a / b;
}
int main() {
auto result = divide(10, 2);
if (result) {
std::cout << "Result: " << *result << std::endl;
} else {
std::cout << "Division by zero" << std::endl;
}
return 0;
}
2. std::variant
std::variant
是一个类型安全的联合体,可以存储多种类型的值。
#include <iostream>
#include <variant>
#include <string>
int main() {
std::variant<int, double, std::string> v;
v = 42;
std::cout << "Holds int: " << std::get<int>(v) << std::endl;
v = 3.14;
std::cout << "Holds double: " << std::get<double>(v) << std::endl;
v = "Hello";
std::cout << "Holds string: " << std::get<std::string>(v) << std::endl;
return 0;
}
七、std::string_view
std::string_view
提供了一个轻量级的、非拥有的字符串视图。
#include <iostream>
#include <string_view>
void printString(std::string_view sv) {
std::cout << sv << std::endl;
}
int main() {
std::string str = "Hello, World!";
printString(str); // 传递 std::string
printString("Direct string literal"); // 传递字符串字面量
return 0;
}
八、并行算法(Parallel Algorithms)
C++17 引入了并行版本的 STL 算法,可以显著提高计算密集型任务的性能。
#include <iostream>
#include <vector>
#include <algorithm>
#include <execution>
int main() {
std::vector<int> vec(1000000, 1);
// 并行执行 std::for_each
std::for_each(std::execution::par, vec.begin(), vec.end(), [](int& n) {
n += 1;
});
// 并行执行 std::sort
std::sort(std::execution::par, vec.begin(), vec.end());
std::cout << "First element: " << vec[0] << std::endl;
return 0;
}
九、文件系统库(Filesystem Library)
C++17 引入了 <filesystem>
库,提供了跨平台的文件系统操作功能。
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::path p = "/path/to/directory";
if (fs::exists(p)) {
std::cout << "Path exists" << std::endl;
if (fs::is_directory(p)) {
std::cout << "It's a directory" << std::endl;
for (const auto& entry : fs::directory_iterator(p)) {
std::cout << entry.path().filename() << std::endl;
}
}
} else {
std::cout << "Path does not exist" << std::endl;
}
return 0;
}
十、其他改进
1. 结构化绑定与 std::tuple
和 std::pair
#include <iostream>
#include <tuple>
int main() {
auto [x, y, z] = std::make_tuple(1, 2.5, "Hello");
std::cout<< x << ", "<< y << ", "<< z << std::endl;
return 0;
}
2. if
和 switch
中的初始化语句
#include <iostream>
#include <optional>
std::optional<int> findValue(const std::vector<int>& vec, int target) {
for (int v : vec) {
if (v == target) return v;
}
return std::nullopt;
}
int main() {
std::vector<int> v = {1, 2, 3};
if (auto it = findValue(v, 2); it) {
std::cout << "Found: " << *it << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
3. [[nodiscard]]
属性
#include <iostream>
[[nodiscard]] int computeValue() {
return 42;
}
int main() {
// 编译器警告:忽略返回值
computeValue();
// 正确用法
int value = computeValue();
std::cout << "Value: " << value << std::endl;
return 0;
}
C++17 引入了许多实用的新特性,使得代码更加简洁、高效和安全。以下是 C++17 的主要新特性总结:
- 结构化绑定:简化了复合类型的解构。
- if 和 switch 中的初始化语句:提高了代码的可读性。
- 内联变量:简化了头文件中的变量定义。
- 折叠表达式:简化了可变参数模板的展开。
-
std::optional
和std::variant
:提供了更安全的值处理方式。 -
std::string_view
:提供了轻量级的字符串视图。 - 并行算法:提高了计算密集型任务的性能。
- 文件系统库:提供了跨平台的文件系统操作功能。