Skip to content

Modern Language Features (C++17/20/23)

Beyond the standard library updates, the C++ language itself has evolved to become more expressive and safe.

Structured Binding (C++17)

Structured binding allows you to unpack tuples, pairs, structs, and arrays into individual variables.

std::pair<int, int> get_coordinates() {
    return {10, 20};
}

auto [x, y] = get_coordinates();
// x = 10, y = 20

// Iterating over a map
std::map<std::string, int> scores;
for (const auto& [name, score] : scores) {
    // ...
}

Modules (C++20)

Modules promise faster build times and better isolation by replacing the textual inclusion of header files (#include).

Basic Module Interface

1
2
3
4
5
6
// math.cppm
export module math;

export int add(int a, int b) {
    return a + b;
}
1
2
3
4
5
6
// main.cpp
import math;

int main() {
    add(1, 2);
}

import std; (C++23)

C++23 standardizes the std module, allowing you to import the entire standard library at once with minimal compile-time cost.

1
2
3
4
5
import std;

int main() {
    std::println("Hello modules!");
}

Coroutines (C++20)

Coroutines allow functions to be suspended and resumed, forming the foundation for async programming and generators.

  • co_await: Suspend execution until a task is done.
  • co_yield: Return a value and suspend (generator).
  • co_return: Finish the coroutine.

Three-way Comparison (<=>) (C++20)

Also known as the "Spaceship Operator". It automatically generates ==, !=, <, <=, >, >=.

#include <compare>

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

    // Default compares members in order
    auto operator<=>(const Version&) const = default;
};

if consteval (C++23)

A safer version of if (std::is_constant_evaluated()). It executes the block only during compile-time evaluation.

1
2
3
4
5
6
7
8
9
consteval int strict_compile_time() { return 42; }

constexpr int func(int x) {
    if consteval {
        return strict_compile_time(); // OK
    } else {
        return x; // Runtime
    }
}

Text Formatting

std::format (C++20)

A type-safe alternative to printf.

std::string s = std::format("Hello, {}!", "World");

std::print (C++23)

Prints formatted text directly to stdout.

std::println("Hello, {}!", "World");