C++20 is a major update to the C++ language, which introduces many new features to make the code more modern, concise and efficient. The following are the main new contents of C++20:
1. Concepts
The concept is used to constrain template parameters to make template programming more intuitive and safe.
#include <concepts> #include <iostream> template <std::integral T> // Constraint T must be an integer typeT add(T a, T b) { return a + b; } int main() { std::cout << add(3, 4) << "\n"; // OK // std::cout << add(3.5, 4.2); // Compile error: double is not an integer}
2. Ranges
C++20 has introducedstd::ranges
To operate the sequence more gracefully.
#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 << " "; // Output: 2 4 } }
3. Coroutines
C++20 introduces coroutines, making asynchronous programming more efficient.
#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(); // Output: Hello,}
4. std::span (lightweight array view)
std::span
Provides safer and more efficient array access without copying data.
#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); // Automatically deduced as span}
5. Three-way comparison operator (<=>, Spaceship Operator)
Introduce three-way comparison operatorsoperator<=>
, simplifies the definition of comparison operators.
#include <iostream> #include <compare> struct Point { int x, y; auto operator<=>(const Point&) const = default; // Automatically generate all comparison operators}; int main() { Point p1{1, 2}, p2{2, 3}; std::cout << (p1 < p2) << "\n"; // Output: 1 (true)}
6. Constexpr Keyword Enhancement
C++20 allowsconstexpr
Functions containtry-catch
Statement and dynamic memory allocation.
#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 introduces modular mechanism to reduce#include
Dependency to improve compilation speed.
// export module mymodule; export int add(int a, int b) { return a + b; } // import mymodule; #include <iostream> int main() { std::cout << add(3, 4) << "\n"; // Output: 7}
8. std::jthread (automatically managed thread)
C++20 introductionstd::jthread
, automatically during destructionjoin()
Thread to prevent resource leakage.
#include <thread> #include <iostream> int main() { std::jthread t([] { std::cout << "Running in thread\n"; }); } // `t` Automatic `join()` without manual management
9. std::bit_cast (efficient type conversion)
std::bit_cast<T>(value)
Used for lossless conversion of POD types, no extra overhead.
#include <bit> #include <iostream> int main() { float f = 3.14f; int i = std::bit_cast<int>(f); std::cout << i << "\n"; // Bit-by-bit conversion, no extra overhead}
10. std::format (format string)
Similarprintf
The formatting API, but is safer.
#include <format> #include <iostream> int main() { std::cout << std::format("Hello, {}!", "world") << "\n"; // Output: Hello, world!}
11. std::ranges::views::zip (package multiple containers)
C++20 providesstd::ranges::views::zip
Let multiple containers iterate simultaneously.
#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 (thread cancellation mechanism)
C++20 introductionstd::stop_token
, used to safely cancel threads.
#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(); // Cancel thread}
Summarize
C++20 is the most important update since C++11. The new features greatly improve the readability, maintainability and performance of the code, mainly including:
- Better template programming: Concept (
concepts
)、if constexpr
- More modern STL:
std::span
、std::format
、std::ranges
- More elegant multi-threading support:
std::jthread
、std::stop_token
- Coroutines (
coroutines
):supportco_await
grammar - Compilation speed optimization: module (
modules
)
C++20 provides a more modern programming method to make development more efficient and safe, and is a version worth learning and using!
This is all about this article about the newly added content of C++20. For more related content of C++20, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!