Přeskočit na obsah

C++20: Velká čtyřka a další

Discover C++20's transformative features: concepts, ranges, the spaceship operator, std::format, designated initializers, std::span, and more.

C++20: A Generational Leap

C++20 is the most significant update to C++ since C++11. It introduces four major features — Concepts, Ranges, Coroutines, and Modules — each of which fundamentally changes how C++ code is written. Beyond the "Big Four," C++20 also brings the spaceship operator,std::format,std::span, designated initializers, and many constexpr enhancements. This lesson covers everything except Coroutines and Modules, which have dedicated lessons.

Concepts: Constraining Templates

Concepts replace SFINAE with readable, composable constraints on template parameters. They produce clear error messages when constraints are not satisfied:

concepts.cpp
#include <iostream>
#include <concepts>
#include <string>
#include <vector>
#include <numeric>

// Define a custom concept
template<typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;

// Use concept in a requires clause
template<typename T>
    requires Numeric<T>
T add(T a, T b) {
    return a + b;
}

// Shorthand syntax — concept as type constraint
auto multiply(Numeric auto a, Numeric auto b) {
    return a * b;
}

// Concept with multiple requirements
template<typename Container>
concept Summable = requires(Container c) {
    { c.begin() } -> std::input_or_output_iterator;
    { c.end() } -> std::input_or_output_iterator;
    { c.size() } -> std::convertible_to<std::size_t>;
};

template<Summable Container>
auto sum_container(const Container& c) {
    using T = typename Container::value_type;
    return std::accumulate(c.begin(), c.end(), T{});
}

int main() {
    std::cout << add(3, 4) << "\n";           // 7
    std::cout << multiply(2.5, 4.0) << "\n";  // 10.0

    std::vector<int> v{1, 2, 3, 4, 5};
    std::cout << sum_container(v) << "\n";     // 15

    // add(std::string("a"), std::string("b"));  // Compile error!
    // Error message: constraints not satisfied — Numeric<std::string> is false

    return 0;
}

Ranges: Composable Algorithms

Rozsahy přinášejí do STL funkční přístup ve stylu potrubí. Pohledy jsou líné – nepřidělují ani nekopírují data a vytvářejí transformace, které se provádějí pouze při iteraci:

ranges.cpp
#include <iostream>
#include <ranges>
#include <vector>
#include <string>
#include <algorithm>

int main() {
    std::vector<int> numbers{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    // Pipeline: filter even, square them, take first 3
    auto result = numbers
        | std::views::filter([](int n) { return n % 2 == 0; })
        | std::views::transform([](int n) { return n * n; })
        | std::views::take(3);

    for (int n : result) {
        std::cout << n << " ";  // 4 16 36
    }
    std::cout << "\n";

    // Range-based algorithms with projections
    struct Employee {
        std::string name;
        int salary;
    };

    std::vector<Employee> team{
        {"Alice", 90000}, {"Bob", 75000}, {"Carol", 120000}
    };

    // Sort by salary using a projection — no custom comparator needed
    std::ranges::sort(team, {}, &Employee::salary);
    for (const auto& e : team) {
        std::cout << e.name << ": " << e.salary << "\n";
    }

    // iota generates an infinite sequence
    for (int i : std::views::iota(1) | std::views::take(5)) {
        std::cout << i << " ";  // 1 2 3 4 5
    }
    std::cout << "\n";

    return 0;
}

Třícestné srovnání a určené inicializátory

Operátor kosmické lodi<=>generuje všech šest porovnávacích operátorů z jediné deklarace. Určené inicializátory přinášejí inicializaci pojmenovaného pole z C do C++ s přidanou bezpečností typu:

spaceship.cpp
#include <iostream>
#include <compare>
#include <string>

struct Version {
    int major;
    int minor;
    int patch;

    // One operator generates ==, !=, <, >, <=, >=
    auto operator<=>(const Version&) const = default;
};

struct Config {
    std::string host = "localhost";
    int port = 8080;
    bool ssl = false;
    int max_connections = 100;
};

int main() {
    Version v1{2, 0, 0};
    Version v2{1, 9, 5};

    if (v1 > v2) std::cout << "v1 is newer\n";  // true
    if (v1 != v2) std::cout << "versions differ\n";

    // Strong ordering gives you all 6 operators for free
    auto cmp = v1 <=> v2;
    if (cmp > 0) std::cout << "v1 > v2\n";

    // Designated initializers — name the fields you're setting
    Config cfg{
        .host = "example.com",
        .port = 443,
        .ssl = true
        // .max_connections keeps its default value (100)
    };

    std::cout << cfg.host << ":" << cfg.port
              << " SSL=" << std::boolalpha << cfg.ssl
              << " max=" << cfg.max_connections << "\n";

    return 0;
}

std::format & std::span

std::formatpřináší formátování řetězců podobné Pythonu do C++.std::spanje nevlastní pohled na souvislou sekvenci prvků, který nahrazuje nezpracované páry ukazatel+velikost:

format_span.cpp
#include <iostream>
#include <format>
#include <span>
#include <vector>
#include <array>

// std::span — works with any contiguous container
void print_values(std::span<const int> data) {
    for (int v : data) {
        std::cout << std::format("{:>5}", v);
    }
    std::cout << "\n";
}

int main() {
    // std::format — type-safe, positional formatting
    std::string msg = std::format("Hello, {}! You are {} years old.", "Alice", 30);
    std::cout << msg << "\n";

    // Format specifiers
    std::cout << std::format("Hex: {:#x}, Oct: {:#o}, Bin: {:#b}\n", 255, 255, 255);
    std::cout << std::format("Pi: {:.4f}\n", 3.14159265);
    std::cout << std::format("{:<15} {:>10}\n", "Name", "Score");
    std::cout << std::format("{:<15} {:>10}\n", "Alice", 95);

    // std::span — unifies arrays, vectors, and raw buffers
    int c_array[] = {1, 2, 3, 4, 5};
    std::vector<int> vec{6, 7, 8, 9, 10};
    std::array<int, 3> arr{11, 12, 13};

    print_values(c_array);  // works with C array
    print_values(vec);      // works with vector
    print_values(arr);      // works with std::array

    // Subspan — slice without copying
    std::span<int> full(vec);
    auto first_three = full.subspan(0, 3);
    print_values(first_three);  //  6  7  8

    return 0;
}

Constexpr Enhancements & Chrono

C++20 masivně rozšiřuje to, co může býtconstexpr: virtuální funkce,dynamic_cast,try-catcha dokoncestd::vectorastd::stringlze nyní používat v kontextu constexpr. To znamená, že více výpočtů trvá kompilaci, což vede k rychlejšímu běhu kódu.

Knihovnazískává úplný kalendář a časové pásmo. Můžete reprezentovat data jako2024y/January/15, provádět aritmetiku kalendáře a převádět mezi časovými pásmy – to vše je typově bezpečné a bez externích knihoven.

Atributy:[[likely]]a[[unlikely]]naznačují kompilátoru, které větve jsou horké cesty, což umožňuje lepší generování kódu v sekcích kritických pro výkon.

Osvědčený postup

Nemusíte používat všechny C++20 najednou. Začněte s funkcemi, které přinášejí největší zvýšení produktivity s nejmenším rušením:

1. Operátor vesmírné lodi – okamžitě přidejteauto operator<=>(const T&) const = default;ke svým typům
2. Koncepty — před psaním vlastních konceptů použijte standardní koncepty (std::integral,std::ranges::range)
3. std::format – nahraďte formátováníprintfastringstream
4. Rozsahy — začněte sstd::views::filterastd::views::transformv novém kódu
5. Určené inicializátory — použijte pro konfigurační struktury a typy voleb

Uložte si Coroutines a moduly, až budou váš tým a toolchain připraveny.

Klíčové poznatky
  • Koncepty nahrazují SFINAE čitelnými, sestavitelnými omezeními šablon a jasnými chybovými zprávami
  • Rozsahy poskytují líné, skládací kanály pomocí operátoru|– nejsou potřeba žádné dočasné kontejnery
  • Operátor kosmické lodi<=>generuje všech šest porovnávacích operátorů z jedné výchozí deklarace
  • std::formatpřináší do C++ typově bezpečné formátování řetězců ve stylu Pythonu
  • std::spanje nevlastní pohled na souvislou paměť, který nahrazuje páry ukazatel+velikost
  • Určené inicializátory ({.field = value}) činí konstrukci struct samodokumentující

Kvíz — Otestujte své znalosti

(20 XP)

1. Co dělá`auto operator<=>(const MyType&) const = default;`?

2. Jaká je hlavní výhoda zobrazení rozsahů (jako je`std::views::filter`)?

3. Jaký problém řeší C++20 Concepts?