C++20 Features
Concepts, ranges, modules
Interview Relevant: Latest standards
C++20 Features
C++20 is a major overhaul, introducing concepts that change how templates are written.
Major Additions
- Concepts: constrain template parameters for better error messages.
- Modules: A new compilation model to replace header files.
- Coroutines: Native support for async programming.
- Ranges: Composable algorithms directly on containers.
- Spaceship Operator (<=>): Automatic three-way comparison.
Code Examples
C++20 major features and improvements.
cpp
1// Concepts
2template<typename T>
3concept Numeric = is_arithmetic_v<T>;
4
5template<Numeric T>
6T add(T a, T b) { return a + b; }
7
8// Ranges
9auto result = vec | views::filter([](int x) { return x > 0; })
10 | views::transform([](int x) { return x * 2; });
11
12// Coroutines
13Generator<int> range(int n) {
14 for (int i = 0; i < n; i++) co_yield i;
15}
16
17// Modules (replacing headers)
18export module math;
19export int add(int a, int b) { return a + b; }
20
21// Three-way comparison (spaceship operator)
22auto result = a <=> b; // Returns ordering
23
24// Designated initializers
25struct Point { int x; int y; };
26Point p = {.x = 1, .y = 2};
27
28// consteval - must be compile-time
29consteval int square(int n) { return n * n; }
30
31// constinit - constant initialization
32constinit int value = 42;
33
34// Abbreviated function templates
35void process(auto x) { } // Same as template<typename T>
36
37// Lambda improvements
38auto lambda = []<typename T>(T x) { }; // Template lambda
39auto lambda2 = [](this auto& self) { }; // Explicit this (C++23)
40
41// std::format
42string s = format("Value: {}", 42);
43
44// std::span
45void process(span<int> data) { }