Tutorials / C++: From Basics to Modern C++ / Modern C++: ranges, concepts and std::format

Modern C++: ranges, concepts and std::format

17 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. Final project: a command-line expense tracker

Why this matters

C++ has changed more in the last decade than in the twenty years before it. A lot of code you find online still reads like 2005. This lesson gathers the features that most improve everyday code. A warning first: compiler and library support arrives feature by feature. Compile with -std=c++20 (or /std:c++20), and if something fails to compile, check your compiler version before blaming your code. For C++23 features use -std=c++23 or /std:c++latest.

std::format (C++20)

Streams are verbose and formatting numbers with them is awkward. std::format uses a pattern string with {} placeholders, similar to Python.

#include <format>
#include <iostream>
#include <string>

int main() {
    std::string name{"Asha"};
    int age{30};
    double balance{1234.5678};

    std::cout << std::format("{} is {} years old\n", name, age);
    std::cout << std::format("balance: {:.2f}\n", balance);        // balance: 1234.57
    std::cout << std::format("[{:>8}] [{:<8}] [{:^8}]\n", "right", "left", "mid");
    std::cout << std::format("hex {:x}, padded {:05d}\n", 255, 42); // hex ff, padded 00042
}

It checks the pattern against the argument types at compile time, so a mismatch is a compile error, not a crash. In C++23, std::print("{} {}\n", a, b) from <print> prints directly and saves the cout wrapper. Library support for std::format arrived in GCC 13, recent MSVC and recent Clang versions; std::print came slightly later. If yours lacks it, the {fmt} library offers the same interface.

Ranges and views

The classic algorithms need two iterators, which is noisy: std::sort(v.begin(), v.end()). The <ranges> library lets you pass the container.

#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>

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

    std::ranges::sort(nums);                       // no begin/end needed
    auto it = std::ranges::find(nums, 8);
    std::cout << "found 8: " << std::boolalpha << (it != nums.end()) << "\n";

    // a pipeline of views: lazy, nothing is computed until we loop
    auto result = nums
                | std::views::filter([](int n) { return n % 2 == 0; })
                | std::views::transform([](int n) { return n * n; });

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

A view is a lightweight description of a sequence. It does not copy the data and it computes lazily, one element at a time as you loop. The pipe | chains steps from left to right, which reads like a sentence: take the numbers, keep the evens, square them. Other useful views are std::views::take(n), drop(n), reverse, keys and values for maps, and iota(a, b) to generate numbers.

for (int i : std::views::iota(1, 6)) std::cout << i << " ";          // 1 2 3 4 5
for (int i : std::views::iota(1) | std::views::take(3)) std::cout << i << " ";   // 1 2 3

One trap: a view refers to the original data. If the vector changes or is destroyed while the view is still in use, you have a dangling view. Also, std::views::filter caches its first match, so mutating elements through a filtered view can behave oddly. Keep views short-lived, built and consumed in the same place.

Concepts

We saw that a template such as maxOf assumes things about T. A concept names those assumptions so the compiler checks them first and reports a short, clear error.

#include <concepts>
#include <iostream>
#include <string>

template <typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;

template <Numeric T>
T twice(T x) { return x * 2; }

template <typename T>
concept Printable = requires(const T& t, std::ostream& os) { os << t; };

template <Printable T>
void show(const T& value) { std::cout << "[" << value << "]\n"; }

int main() {
    std::cout << twice(21) << " " << twice(1.5) << "\n";    // 42 3
    show(std::string{"ok"});
    // twice(std::string{"no"});   // error: constraints not satisfied
}

The standard provides many ready-made concepts in <concepts>, such as std::integral, std::same_as, std::convertible_to and std::invocable. A requires expression lets you describe what operations a type must support, as Printable does. A shorthand also exists: auto parameters in functions make them templates, and void show(const Printable auto& v) is the same as the longer form.

std::span

A std::span<T> (C++20) is a non-owning view of a contiguous block, like string_view but for any element type. It lets one function accept a vector, an array or a raw array with its size, without templates or pointer-and-length pairs.

#include <array>
#include <span>
#include <vector>

double average(std::span<const double> values) {
    if (values.empty()) return 0.0;
    double sum = 0;
    for (double v : values) sum += v;
    return sum / static_cast<double>(values.size());
}

int main() {
    std::vector<double> a{1, 2, 3};
    std::array<double, 2> b{10, 20};
    double c[]{4, 5, 6, 7};
    std::cout << average(a) << " " << average(b) << " " << average(c) << "\n";   // 2 15 5.5
}

Small things that add up

  • Designated initialisers: Point p{.x = 1, .y = 2}; (C++20, fields in declaration order).
  • contains on maps and sets, starts_with and ends_with on strings.
  • std::erase_if for any standard container.
  • std::numbers::pi in <numbers>.
  • C++23: std::expected, std::print, std::flat_map in newer libraries, and the if consteval statement. Support differs by compiler, so test before relying on any of them.

The common mistake

Assuming a feature works because it is in the standard. Standards describe the language, compilers implement it over several years. When something does not compile, check the version first, and the cppreference compiler support table, then the flag -std. The other mistake is chaining a long pipeline of views into one unreadable expression. Name the intermediate steps.

Try it yourself

  1. Use std::views::iota, filter and transform to print the squares of all odd numbers below 20.
  2. Write a concept HasSize that requires a .size() member, and a function that uses it.
  3. Rewrite one of your earlier programs to print using std::format in place of the stream operators.
cpp
#include <format>
#include <iostream>
#include <string>

int main() {
    std::string name{"Asha"};
    int age{30};
    double balance{1234.5678};

    std::cout << std::format("{} is {} years old\n", name, age);
    std::cout << std::format("balance: {:.2f}\n", balance);        // balance: 1234.57
    std::cout << std::format("[{:>8}] [{:<8}] [{:^8}]\n", "right", "left", "mid");
    std::cout << std::format("hex {:x}, padded {:05d}\n", 255, 42); // hex ff, padded 00042
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account