Topic 15 of 27 · Expert
Modern C++ Features (17/20/23)
Structured bindings, optional, variant, ranges and more.
Concept
C++17: structured bindings, std::optional (maybe a value), std::variant (type-safe union), std::string_view (non-owning string), if constexpr.
C++20: concepts, ranges and views, coroutines, modules, std::span, designated initialisers and three-way comparison.
C++23 adds std::expected for error handling, std::print and more range adaptors.
Code (C++20)
#include <iostream>
#include <map>
#include <optional>
#include <ranges>
#include <variant>
#include <vector>
std::optional<int> findIndex(const std::vector<int>& v, int x) {
for (int i = 0; i < (int)v.size(); ++i) if (v[i] == x) return i;
return std::nullopt;
}
int main() {
std::map<std::string, int> ctc{{"TCS", 7}, {"Infosys", 6}};
for (const auto& [company, lpa] : ctc) std::cout << company << ' ' << lpa << '\n';
std::vector<int> v{1, 2, 3, 4, 5, 6};
for (int x : v | std::views::filter([](int n) { return n % 2 == 0; })
| std::views::transform([](int n) { return n * n; }))
std::cout << x << ' '; // 4 16 36
std::variant<int, std::string> val = "hello";
std::cout << std::get<std::string>(val) << ' ' << findIndex(v, 4).value_or(-1) << '\n';
}Remember
- optional for maybe-values, not pointers.
- Views are lazy and composable.
- string_view must not outlive its source.
Interview questions
optional vs variant?
optional<T> holds a T or nothing; variant<A, B> holds exactly one of several types, checked at run time.
Name three C++20 features.
Concepts, ranges, coroutines (also modules, span, <=>).
Lesson test
Take an 8-question test on “Modern C++ Features (17/20/23)” — concepts, output prediction, bug spotting and interview questions.