Modern C++: ranges, concepts and std::format
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- 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). containson maps and sets,starts_withandends_withon strings.std::erase_iffor any standard container.std::numbers::piin<numbers>.- C++23:
std::expected,std::print,std::flat_mapin newer libraries, and theif constevalstatement. 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
- Use
std::views::iota,filterandtransformto print the squares of all odd numbers below 20. - Write a concept
HasSizethat requires a.size()member, and a function that uses it. - Rewrite one of your earlier programs to print using
std::formatin place of the stream operators.
#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