SoFunction
Updated on 2025-04-14

A brief discussion on the new contents of C++20

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::rangesTo operate the sequence more gracefully.

#include &lt;ranges&gt;
#include &lt;vector&gt;
#include &lt;iostream&gt;

int main() {
    std::vector&lt;int&gt; v = {1, 2, 3, 4, 5};
    for (int x : v | std::views::filter([](int n) { return n % 2 == 0; })) {
        std::cout &lt;&lt; x &lt;&lt; " ";  // Output: 2 4    }
}

3. Coroutines

C++20 introduces coroutines, making asynchronous programming more efficient.

#include &lt;coroutine&gt;
#include &lt;iostream&gt;

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 &lt;&lt; "Hello, ";
    co_await std::suspend_always{};
    std::cout &lt;&lt; "World!\n";
}

int main() {
    example();  // Output: Hello,}

4. std::span (lightweight array view)

std::spanProvides safer and more efficient array access without copying data.

#include &lt;span&gt;
#include &lt;iostream&gt;

void print(std::span&lt;int&gt; s) {
    for (int n : s) std::cout &lt;&lt; n &lt;&lt; " ";
}

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 &lt;iostream&gt;
#include &lt;compare&gt;

struct Point {
    int x, y;
    auto operator&lt;=&gt;(const Point&amp;) const = default;  // Automatically generate all comparison operators};

int main() {
    Point p1{1, 2}, p2{2, 3};
    std::cout &lt;&lt; (p1 &lt; p2) &lt;&lt; "\n";  // Output: 1 (true)}

6. Constexpr Keyword Enhancement

C++20 allowsconstexprFunctions containtry-catchStatement 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#includeDependency to improve compilation speed.

// 
export module mymodule;
export int add(int a, int b) { return a + b; }

// 
import mymodule;
#include &lt;iostream&gt;

int main() {
    std::cout &lt;&lt; add(3, 4) &lt;&lt; "\n";  // Output: 7}

8. std::jthread (automatically managed thread)

C++20 introductionstd::jthread, automatically during destructionjoin()Thread to prevent resource leakage.

#include &lt;thread&gt;
#include &lt;iostream&gt;

int main() {
    std::jthread t([] { std::cout &lt;&lt; "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 &lt;bit&gt;
#include &lt;iostream&gt;

int main() {
    float f = 3.14f;
    int i = std::bit_cast&lt;int&gt;(f);
    std::cout &lt;&lt; i &lt;&lt; "\n";  // Bit-by-bit conversion, no extra overhead}

10. std::format (format string)

SimilarprintfThe formatting API, but is safer.

#include &lt;format&gt;
#include &lt;iostream&gt;

int main() {
    std::cout &lt;&lt; std::format("Hello, {}!", "world") &lt;&lt; "\n";  // Output: Hello, world!}

11. std::ranges::views::zip (package multiple containers)

C++20 providesstd::ranges::views::zipLet 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 &lt;iostream&gt;
#include &lt;thread&gt;
#include &lt;stop_token&gt;

void task(std::stop_token st) {
    while (!st.stop_requested()) {
        std::cout &lt;&lt; "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::spanstd::formatstd::ranges
  • More elegant multi-threading support:std::jthreadstd::stop_token
  • Coroutines (coroutines):supportco_awaitgrammar
  • 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!