After this lesson, you will be able to: Use modern C++17/20 features: structured bindings, std::optional, std::variant, std::span, ranges, concepts.
C++17 and C++20 added features that make C++ feel less like 1990s C++ and more like a modern language. Use them.
Destructure tuples, pairs, structs, arrays.
#include <map>#include <tuple>std::map<std::string, int> ages = {{"Alex", 30}, {"Sam", 25}};for (const auto& [name, age] : ages) {std::cout << name << " is " << age << "\n";}// Return multiple valuesstd::tuple<int, std::string> getData() { return {42, "hello"}; }auto [num, text] = getData();// Decompose a structstruct Point { int x; int y; };Point p = {3, 4};auto [x, y] = p;
A value that might not be there, no nullable pointers needed.
#include <optional>std::optional<User> findUser(int id) {if (id == 1) return User("Alex", 30);return std::nullopt;}auto u = findUser(2);if (u) {std::cout << u->name() << "\n";}// u.value_or(defaultUser) for fallback
Sum types in C++.
#include <variant>std::variant<int, std::string, double> v = 42;v = std::string("hello");// std::visit applies the right overloadstd::visit([](const auto& val) {std::cout << "value: " << val << "\n";}, v);
Replaces `T*` + size pairs.
#include <span>#include <vector>void process(std::span<int> data) {for (int x : data) std::cout << x << " ";}std::vector<int> v = {1, 2, 3};int arr[] = {4, 5, 6};process(v); // works with vectorprocess(arr); // works with C arrayprocess({v.data() + 1, 2}); // works with pointer + size
Composable lazy pipelines.
#include <ranges>#include <vector>std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};auto pipeline = nums| std::views::filter([](int x) { return x % 2 == 0; })| std::views::transform([](int x) { return x * x; })| std::views::take(3);for (int x : pipeline) std::cout << x << " ";// outputs: 4 16 36
Storing references in std::optional (use std::optional<std::reference_wrapper<T>>). Skipping the `auto& [a, b] = ...` form when you want to modify (you'll get copies). Not checking optional before dereferencing (`*opt` on empty = UB). Sticking to C++11/14 syntax when C++20 is available, older code reads as 'didn't keep up.'
Sign in and purchase access to unlock this lesson.