C++ · Module 17 · Lesson 11 min read

Tour of Modern C++: C++11 to C++23

C++11 — "a new language"

auto, range-based for, lambdas, nullptr, move semantics & rvalue references, smart pointers (unique_ptr, shared_ptr), constexpr, override/final, enum class, uniform {} initialization, variadic templates, std::thread/mutex/atomic, std::array, unordered_map, std::function, static_assert, user-defined literals

C++14 — polishing

Generic lambdas (auto parameters), std::make_unique, return type deduction, relaxed constexpr (loops), digit separators 1'000'000, binary literals 0b1010

C++17 — convenience

Structured bindings auto [a, b], if/switch with initializers, if constexpr, std::optional, std::variant, std::any, std::string_view, std::filesystem, fold expressions, CTAD, inline variables, [[nodiscard]], parallel algorithms, guaranteed copy elision

C++20 — the "big four" + more

  • Concepts (constrained templates)
  • Ranges (views and pipelines)
  • Coroutines (co_await, co_yield)
  • Modules (import) Plus: <=> spaceship, std::format, std::span, consteval, designated initializers {.x = 1}, std::jthread, contains(), starts_with(), std::erase_if, calendar & time zones in <chrono>, std::source_location

C++23 — filling gaps

std::print/println, std::expected, std::ranges::to, views::enumerate/zip/chunk, std::generator, deducing this, std::flat_map, std::mdspan, std::stacktrace, if consteval, import std;

Writing modern C++ ✅

  • auto where it helps readability
  • Containers and smart pointers instead of raw arrays and new
  • const, constexpr, noexcept where they apply
  • Algorithms and ranges instead of hand-written loops
  • std::format/std::print for output
  • Compile with -std=c++20 (or newer) and -Wall -Wextra

Compiler support

Check cppreference.com's "compiler support" page; GCC, Clang and MSVC support nearly all of C++20 and most of C++23.

Running this example

It uses C++23 features (std::print, std::expected): compile with -std=c++23 on GCC 14+, a recent Clang with libc++, or MSVC 2022 17.7+.

Example

C++
#include <algorithm>
#include <expected>
#include <format>
#include <map>
#include <memory>
#include <optional>
#include <print>
#include <ranges>
#include <string>
#include <vector>

struct Expense {                                  // C++20 designated initializers below
    std::string category;
    double amount = 0;
    auto operator<=>(const Expense&) const = default;      // C++20
};

std::expected<double, std::string> parse(const std::string& s) {   // C++23
    try { return std::stod(s); } catch (...) { return std::unexpected("bad number: " + s); }
}

int main() {
    auto list = std::make_unique<std::vector<Expense>>();                      // C++14
    list->push_back({ .category = "Food", .amount = 450 });                     // C++20
    list->push_back({ .category = "Rent", .amount = 15000 });
    list->push_back({ .category = "Food", .amount = 1200 });

    std::map<std::string, double> totals;
    for (const auto& [cat, amount] : *list) totals[cat] += amount;              // C++17
    for (const auto& [cat, total] : totals) std::println("{:<6}{:>10.2f}", cat, total);   // C++23 print

    auto big = *list | std::views::filter([](const Expense& e) { return e.amount > 1000; })   // C++20
                     | std::views::transform(&Expense::category);
    std::print("big expenses:");
    for (const auto& c : big) std::print(" {}", c);
    std::println("");

    if (auto it = totals.find("Rent"); it != totals.end())                      // C++17
        std::println("rent share: {:.1f}%", it->second / (totals["Food"] + it->second) * 100);

    std::optional<std::string> coupon;                                          // C++17
    std::println("coupon: {}", coupon.value_or("none"));
    for (const char* s : { "99.5", "x" }) {
        auto r = parse(s);
        std::println("parse(\"{}\") -> {}", s, r ? std::format("{}", *r) : r.error());
    }
    std::println("contains Food? {}", totals.contains("Food"));                 // C++20
    std::println("sorted max: {}", std::ranges::max(*list).category);
    return 0;
}

/* Output:
Food     1650.00
Rent    15000.00
big expenses: Rent Food
rent share: 90.1%
coupon: none
parse("99.5") -> 99.5
parse("x") -> bad number: x
contains Food? true
sorted max: Rent
*/