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 提供了更現代化的編程方式,使開發更加 高效、安全,是值得學習和使用的版本!