C++20 is the biggest change to the language since C++11. C++14 and C++17 were mostly polish. C++20 changes how you write generic code, how you process sequences, how you structure async work, and how you organise a codebase.
The headline features are often called the “big four”: concepts, ranges, coroutines and modules. Add the three-way comparison operator and a long list of smaller library wins, and day-to-day C++ looks noticeably different.
This post walks through each feature with a short C++17-vs-C++20 comparison. It assumes you already write modern C++ (11/14/17) and want to know what is worth adopting first.
1. Concepts: templates that say what they need
Concepts let you put named requirements on template parameters. Before C++20, the usual tool was SFINAE with std::enable_if. It worked, but it was hard to read, and a wrong type produced pages of error messages.
C++17:
template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>T gcd(T a, T b) { return b == 0 ? a : gcd(b, a % b);}
C++20:
template <std::integral T>T gcd(T a, T b) { return b == 0 ? a : gcd(b, a % b);}// Or, with abbreviated function templates:auto twice(std::integral auto x) { return x * 2; }
You can also define your own concepts with a requires expression:
template <typename T>concept Hashable = requires(T a) { { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;};
Why it matters:
- The constraint is part of the signature, so the code documents itself.
- Errors say which requirement failed, instead of dumping template instantiation traces.
- Overloading on constraints is clean: the compiler picks the most constrained match, so tag dispatch is rarely needed.
- The standard library ships ready-made concepts in
<concepts>and<iterator>, such asstd::integral,std::same_asandstd::random_access_iterator.
2. Ranges: algorithms on whole containers, composed lazily
Ranges let you pass a container straight to an algorithm and chain transformations with |. Views are lazy: nothing is computed until you iterate, and no temporary containers are created.
C++17: square the even numbers, keep the first three.
std::vector<int> evens;std::copy_if(v.begin(), v.end(), std::back_inserter(evens), [](int n) { return n % 2 == 0; });std::vector<int> result;for (std::size_t i = 0; i < evens.size() && i < 3; ++i) result.push_back(evens[i] * evens[i]);
C++20:
namespace views = std::views;auto result = v | views::filter([](int n) { return n % 2 == 0; }) | views::transform([](int n) { return n * n; }) | views::take(3);std::ranges::sort(v); // no more v.begin(), v.end()
Why it matters:
- No more mismatched iterator pairs like
sort(a.begin(), b.end()). - Pipelines read top to bottom in the order the data flows.
- Lazy evaluation avoids intermediate copies.
- Range algorithms support projections, for example
std::ranges::sort(people, {}, &Person::age);.
One gap to know about: C++20 has no std::ranges::to for turning a view back into a container. That arrived in C++23. In C++20 you build the container from the view’s begin() and end(), or loop over it.
3. Coroutines: async code that reads like sync code
A coroutine is a function that can suspend and resume later. Any function that uses co_await, co_yield or co_return is a coroutine. Its state lives in a frame the compiler manages, so you no longer write callback chains or hand-rolled state machines.
C++17: async work usually means callbacks or futures.
fetch_user(id, [](User u) { fetch_orders(u, [](Orders o) { render(o); });});
C++20:
Task<void> show_orders(int id) { User u = co_await fetch_user(id); Orders o = co_await fetch_orders(u); render(o);}Generator<int> naturals() { for (int i = 0;; ++i) co_yield i; // lazy, infinite sequence}
Why it matters:
- Async I/O, networking and pipelines become linear and easy to follow.
- Generators produce values on demand without building a container.
- Coroutines are stackless, so each suspended coroutine costs only its frame, not a whole thread stack.
The caveat: C++20 shipped the language machinery but almost no library types. Task and Generator above are not in the C++20 standard library. You write them yourself or take them from a library such as cppcoro, Boost.Asio or folly. (std::generator arrived in C++23.)
4. Modules: an end to the header model
Modules replace textual #include with compiled interfaces. A module is compiled once, and importing it does not re-parse its source in every translation unit.
C++17:
// math.h SQUARE(x)// leaks into every includerint add(int a, int b);// main.cpp "math.h"
C++20:
// math.cppmexport module math;export int add(int a, int b) { return a + b; }int helper() { return 42; } // not exported, stays private// main.cppimport math;int main() { return add(1, 2); }
Why it matters:
- Faster builds: large headers are parsed once, not once per
.cppfile. - Isolation: macros and non-exported names do not leak to importers.
- Order independence: the order of
importstatements does not change meaning, unlike#include. - No include guards and no separate header and source files to keep in sync.
The caveat: modules were the slowest C++20 feature to become usable. They need build-system support (CMake 3.28 or later is the usual starting point) and behaviour still differs between compilers. Many teams start by consuming modules or using header units before converting their own code.
5. Three-way comparison: one operator instead of six
The “spaceship” operator <=> compares two values once and reports less, equal or greater. When you default it, the compiler writes every comparison for you.
C++17:
struct Version { int major, minor, patch; bool operator==(const Version& o) const { return std::tie(major, minor, patch) == std::tie(o.major, o.minor, o.patch); } bool operator<(const Version& o) const { return std::tie(major, minor, patch) < std::tie(o.major, o.minor, o.patch); } bool operator!=(const Version& o) const { return !(*this == o); } bool operator> (const Version& o) const { return o < *this; } bool operator<=(const Version& o) const { return !(o < *this); } bool operator>=(const Version& o) const { return !(*this < o); }};
C++20:
struct Version { int major, minor, patch; auto operator<=>(const Version&) const = default;};
Why it matters:
- One line replaces six operators, and there is no boilerplate to get wrong.
- Members are compared in declaration order, which is usually what you want.
- The result type (
std::strong_ordering,std::weak_orderingorstd::partial_ordering) states what kind of ordering the type has. - C++20 also rewrites
a != bas!(a == b), so defining==alone gives you!=for free.
6. Smaller wins you will use every day
The big four get the headlines, but these smaller additions often pay off sooner because they need no build changes.
| Feature | Header | Replaces in C++17 | C++20 example |
|---|---|---|---|
std::format | <format> | printf (not type-safe) or ostringstream (verbose) | std::format("{} is {:.1f}%", name, pct) |
std::span | <span> | Pointer + length pairs | void process(std::span<const int> data); |
| Designated initializers | language | Positional aggregate init | Config c{.port = 8080, .verbose = true}; |
contains() | <map>, <set> | m.find(k) != m.end() or m.count(k) | if (m.contains(k)) |
starts_with / ends_with | <string> | s.compare(0, p.size(), p) == 0 | if (path.ends_with(".log")) |
std::jthread | <thread> | std::thread + manual join() | Joins in its destructor and supports cooperative stop via std::stop_token |
consteval | language | constexpr that might run at runtime | consteval int sq(int n) { return n * n; } always runs at compile time |
constinit | language | Hoping a global was constant-initialised | constinit int counter = 0; stops the static init order problem |
| Calendar and time zones | <chrono> | Third-party date libraries | 2026y / November / 22d, std::chrono::zoned_time |
using enum | language | Repeating Color:: in every case | using enum Color; inside a switch |
[[likely]] / [[unlikely]] | language | Compiler-specific __builtin_expect | if (err) [[unlikely]] { ... } |
std::bit_cast | <bit> | memcpy or reinterpret_cast type punning | auto bits = std::bit_cast<std::uint32_t>(1.0f); |
Two of these deserve a closer look.
std::format gives you Python-style formatting that is type-checked at compile time:
// C++17std::ostringstream os;os << "User " << id << " has " << std::fixed << std::setprecision(2) << balance;// C++20auto msg = std::format("User {} has {:.2f}", id, balance);
std::span is a non-owning view over contiguous memory. One function signature now accepts a C array, a std::array or a std::vector:
double average(std::span<const double> xs) { return std::accumulate(xs.begin(), xs.end(), 0.0) / xs.size();}average(my_vector);average(my_std_array);average(raw_array);
Lambdas improved too. C++20 allows template parameter lists on lambdas ([]<typename T>(std::vector<T>& v) { ... }), default-constructible stateless lambdas, and lambdas in unevaluated contexts. constexpr also grew much stronger: std::vector and std::string can now be used at compile time, as can virtual functions and try blocks.
7. Adopting C++20 today
For most of C++20 the compilers are ready. Modules are the exception: in 2026 the compilers support them, but much of the surrounding tooling still does not.
- Concepts, ranges, coroutines,
<=>,std::format,std::span: supported in current GCC, Clang and MSVC. GCC 16 now defaults to GNU C++20. - Modules: MSVC has had them since VS 2022 17.6; GCC 15 and Clang 22 are listed as supporting them (arewemodulesyet.org). GCC 16’s release notes still call modules experimental, and they must be enabled with
-fmodules. - Tooling is the bottleneck: Visual Studio 2026 IntelliSense still labels modules support as experimental (Mathieu Ropert, April 2026). Many build tools and caches have only partial support.
A practical order for migrating a C++17 codebase:
- Switch the build to
-std=c++20(or/std:c++20) and fix the few breaking changes, such as the comparison rewrite rules andu8string literals becomingchar8_t. - Adopt the drop-in library wins:
contains(),starts_with,std::span,std::format,std::jthread. - Replace hand-written comparison operators with
= default<=>. - Replace
enable_ifwith concepts in new and frequently touched templates. - Use ranges in new code, and convert loops opportunistically.
- Introduce coroutines where you already have async I/O, using a proven library for
Taskand generator types. - Pilot modules on one self-contained component, and only after checking that your build system, IDE and CI caches handle them.
Conclusion
C++20 is worth adopting for concepts, <=> and the library additions alone. Those features cut boilerplate and give clearer errors from the day you switch compilers. Ranges and coroutines change how you structure code, and both reward a gradual rollout. Modules promise the biggest long-term gain in build times and isolation, but still need tooling to catch up.
If your codebase is on C++17, the switch is low-risk and pays off quickly. Start with the easy wins and let the larger features follow as your team gets comfortable.
Leave a Reply