C++20 是 C++ 语言的一次重大更新,它引入了许多新特性,使代码更现代化、简洁且高效。以下是 C++20 的主要新增内容:
1. 概念(Concepts)
概念用于约束模板参数,使模板编程更加直观和安全。
#include <concepts>
#include <iostream>template <std::integral T> // 约束 T 必须是整数类型
T add(T a, T b) {return a + b;
}int main() {std::cout << add(3, 4) << "\n"; // OK// std::cout << add(3.5, 4.2); // 编译错误:double 不是整数
}
2. 范围库(Ranges)
C++20 引入了 std::ranges
以更优雅地操作序列。
#include <ranges>
#include <vector>
#include <iostream>int main() {std::vector<int> v = {1, 2, 3, 4, 5};for (int x : v | std::views::filter([](int n) { return n % 2 == 0; })) {std::cout << x << " "; // 输出: 2 4}
}
3. 协程(Coroutines)
C++20 引入了协程,使得异步编程更加高效。
#include <coroutine>
#include <iostream>struct Task {struct promise_type {Task get_return_object() { return {}; }std::suspend_never initial_suspend() { return {}; }std::suspend_never final_suspend() noexcept { return {}; }void return_void() {}void unhandled_exception() {}};
};Task example() {std::cout << "Hello, ";co_await std::suspend_always{};std::cout << "World!\n";
}int main() {example(); // 输出: Hello,
}
4. std::span
(轻量级数组视图)
std::span
提供更安全和高效的数组访问方式,无需拷贝数据。
#include <span>
#include <iostream>void print(std::span<int> s) {for (int n : s) std::cout << n << " ";
}int main() {int arr[] = {1, 2, 3, 4, 5};print(arr); // 自动推导为 span
}
5. 三路比较运算符(<=>
,Spaceship Operator)
引入三路比较运算符 operator<=>
,简化比较运算符的定义。
#include <iostream>
#include <compare>struct Point {int x, y;auto operator<=>(const Point&) const = default; // 自动生成所有比较运算符
};int main() {Point p1{1, 2}, p2{2, 3};std::cout << (p1 < p2) << "\n"; // 输出: 1 (true)
}
6. constexpr
关键字增强
C++20 允许 constexpr
函数包含 try-catch
语句和动态内存分配。
#include <vector>constexpr int sum(const std::vector<int>& v) {int total = 0;for (int n : v) total += n;return total;
}int main() {constexpr std::vector<int> v = {1, 2, 3, 4, 5};static_assert(sum(v) == 15);
}
7. 模块(Modules)
C++20 引入模块化机制,减少 #include
依赖,提高编译速度。
// mymodule.cpp
export module mymodule;
export int add(int a, int b) { return a + b; }// main.cpp
import mymodule;
#include <iostream>int main() {std::cout << add(3, 4) << "\n"; // 输出: 7
}
8. std::jthread
(自动管理的线程)
C++20 引入 std::jthread
,在析构时自动 join()
线程,防止资源泄露。
#include <thread>
#include <iostream>int main() {std::jthread t([] { std::cout << "Running in thread\n"; });
} // `t` 自动 `join()`,无需手动管理
9. std::bit_cast
(高效的类型转换)
std::bit_cast<T>(value)
用于无损转换 POD 类型,无额外开销。
#include <bit>
#include <iostream>int main() {float f = 3.14f;int i = std::bit_cast<int>(f);std::cout << i << "\n"; // 按位转换,无额外开销
}
10. std::format
(格式化字符串)
类似 printf
的格式化 API,但更安全。
#include <format>
#include <iostream>int main() {std::cout << std::format("Hello, {}!", "world") << "\n"; // 输出: Hello, world!
}
11. std::ranges::views::zip
(打包多个容器)
C++20 提供 std::ranges::views::zip
让多个容器同步迭代。
#include <ranges>
#include <vector>
#include <iostream>int main() {std::vector<int> a = {1, 2, 3};std::vector<std::string> b = {"one", "two", "three"};for (auto [x, y] : std::views::zip(a, b)) {std::cout << x << " -> " << y << "\n";}
}
12. std::stop_token
(线程取消机制)
C++20 引入 std::stop_token
,用于安全地取消线程。
#include <iostream>
#include <thread>
#include <stop_token>void task(std::stop_token st) {while (!st.stop_requested()) {std::cout << "Working...\n";std::this_thread::sleep_for(std::chrono::milliseconds(500));}
}int main() {std::jthread t(task);std::this_thread::sleep_for(std::chrono::seconds(2));t.request_stop(); // 取消线程
}
总结
C++20 是 C++11 以来最重要的一次更新,新增的特性大大提升了代码的 可读性、可维护性 和 性能,主要包括:
- 更好的模板编程:概念 (
concepts
)、if constexpr
- 更现代的 STL:
std::span
、std::format
、std::ranges
- 更优雅的多线程支持:
std::jthread
、std::stop_token
- 协程 (
coroutines
):支持co_await
语法 - 编译速度优化:模块 (
modules
)
C++20 提供了更现代化的编程方式,使开发更加 高效、安全,是值得学习和使用的版本!