# C++20
NOTE: this is a web “mirror” of Anthony Calandra’s modern-cpp-features shared under MIT License (see at bottom). The only reason I do a copy is I hate reading markdowns from github. I want something simple and plain for my own reference.
# Overview
Many of these descriptions and examples are taken from various resources (see Acknowledgements section) and summarized in my own words.
C++20 includes the following new language features:
- coroutines
- concepts
- three-way comparison
- designated initializers
- template syntax for lambdas
- range-based for loop with initializer
- \[\[likely\]] and \[\[unlikely\]] attributes
- deprecate implicit capture of this
- class types in non-type template parameters
- constexpr virtual functions
- explicit(bool)
- immediate functions
- using enum
- lambda capture of parameter pack
- char8_t
- constinit
- __VA_OPT__
C++20 includes the following new library features:
- concepts library
- formatting library
- synchronized buffered outputstream
- std::span
- bit operations
- math constants
- std::is_constant_evaluated
- std::make_shared supports arrays
- starts_with and ends_with on strings
- check if associative container has element
- std::bit_cast
- std::midpoint
- std::to_array
- std::bind_front
- uniform container erasure
- three-way comparison helpers
- std::lexicographical_compare_three_way
# C++20 Language Features
# Coroutines
Note: While these examples illustrate how to use coroutines at a basic level, there is lots more going on when the code is compiled. These examples are not meant to be complete coverage of C++20’s coroutines. Since the
generator
andtask
classes are not provided by the standard library yet, I used the cppcoro library to compile these examples.
Coroutines are special functions that can have their execution suspended and resumed. To define a coroutine, the co_return
, co_await
, or co_yield
keywords must be present in the function’s body. C++20’s coroutines are stackless; unless optimized out by the compiler, their state is allocated on the heap.
An example of a coroutine is a generator function, which yields (i.e. generates) a value at each invocation:
|
|
The above range
generator function generates values starting at start
until end
(exclusive), with each iteration step yielding the current value stored in start
. The generator maintains its state across each invocation of range
(in this case, the invocation is for each iteration in the for loop). co_yield
takes the given expression, yields (i.e. returns) its value, and suspends the coroutine at that point. Upon resuming, execution continues after the co_yield
.
Another example of a coroutine is a task, which is an asynchronous computation that is executed when the task is awaited:
|
|
In this example, the co_await
keyword is introduced. This keyword takes an expression and suspends execution if the thing you’re awaiting on (in this case, the read or write) is not ready, otherwise you continue execution. (Note that under the hood, co_yield
uses co_await
.)
Using a task to lazily evaluate a value:
|
|
# Concepts
Concepts are named compile-time predicates which constrain types. They take the following form:
template < template-parameter-list >
concept concept-name = constraint-expression;
where constraint-expression
evaluates to a constexpr Boolean. Constraints should model semantic requirements, such as whether a type is a numeric or hashable. A compiler error results if a given type does not satisfy the concept it’s bound by (i.e. constraint-expression
returns false
). Because constraints are evaluated at compile-time, they can provide more meaningful error messages and runtime safety.
|
|
There are a variety of syntactic forms for enforcing concepts:
|
|
The requires
keyword is used either to start a requires
clause or a requires
expression:
|
|
Note that the parameter list in a requires
expression is optional. Each requirement in a requires
expression are one of the following:
- Simple requirements - asserts that the given expression is valid.
|
|
- Type requirements - denoted by the
typename
keyword followed by a type name, asserts that the given type name is valid.
|
|
- Compound requirements - an expression in braces followed by a trailing return type or type constraint.
|
|
- Nested requirements - denoted by the
requires
keyword, specify additional constraints (such as those on local parameter arguments).
|
|
See also: concepts library.
# Three-way comparison
C++20 introduces the spaceship operator (<=>
) as a new way to write comparison functions that reduce boilerplate and help developers define clearer comparison semantics. Defining a three-way comparison operator will autogenerate the other comparison operator functions (i.e. ==
, !=
, <
, etc.).
Three orderings are introduced:
std::strong_ordering
: The strong ordering distinguishes between items being equal (identical and interchangeable). Providesless
,greater
,equivalent
, andequal
ordering. Examples of comparisons: searching for a specific value in a list, values of integers, case-sensitive strings.std::weak_ordering
: The weak ordering distinguishes between items being equivalent (not identical, but can be interchangeable for the purposes of comparison). Providesless
,greater
, andequivalent
ordering. Examples of comparisons: case-insensitive strings, sorting, comparing some but not all visible members of a class.std::partial_ordering
: The partial ordering follows the same principle of weak ordering but includes the case when an ordering isn’t possible. Providesless
,greater
,equivalent
, andunordered
ordering. Examples of comparisons: floating-point values (e.g.NaN
).
A defaulted three-way comparison operator does a member-wise comparison:
|
|
You can also define your own comparisons:
|
|
# Designated initializers
C-style designated initializer syntax. Any member fields that are not explicitly listed in the designated initializer list are default-initialized.
|
|
# Template syntax for lambdas
Use familiar template syntax in lambda expressions.
|
|
# Range-based for loop with initializer
This feature simplifies common code patterns, helps keep scopes tight, and offers an elegant solution to a common lifetime problem.
|
|
# \[\[likely\]] and \[\[unlikely\]] attributes
Provides a hint to the optimizer that the labelled statement has a high probability of being executed.
|
|
If one of the likely/unlikely attributes appears after the right parenthesis of an if-statement, it indicates that the branch is likely/unlikely to have its substatement (body) executed.
|
|
It can also be applied to the substatement (body) of an iteration statement.
|
|
# Deprecate implicit capture of this
Implicitly capturing this
in a lambda capture using [=]
is now deprecated; prefer capturing explicitly using [=, this]
or [=, *this]
.
|
|
# Class types in non-type template parameters
Classes can now be used in non-type template parameters. Objects passed in as template arguments have the type const T
, where T
is the type of the object, and has static storage duration.
|
|
# constexpr virtual functions
Virtual functions can now be constexpr
and evaluated at compile-time. constexpr
virtual functions can override non-constexpr
virtual functions and vice-versa.
|
|
# explicit(bool)
Conditionally select at compile-time whether a constructor is made explicit or not. explicit(true)
is the same as specifying explicit
.
|
|
# Immediate functions
Similar to constexpr
functions, but functions with a consteval
specifier must produce a constant. These are called immediate functions
.
|
|
# using enum
Bring an enum’s members into scope to improve readability. Before:
|
|
After:
|
|
# Lambda capture of parameter pack
Capture parameter packs by value:
|
|
Capture parameter packs by reference:
|
|
# char8_t
Provides a standard type for representing UTF-8 strings.
|
|
# constinit
The constinit
specifier requires that a variable must be initialized at compile-time.
|
|
# __VA_OPT__
Helps support variadic macros by evaluating to the given argument if the variadic macro is non-empty.
|
|
# C++20 Library Features
# Concepts library
Concepts are also provided by the standard library for building more complicated concepts. Some of these include:
Core language concepts:
same_as
- specifies two types are the same.derived_from
- specifies that a type is derived from another type.convertible_to
- specifies that a type is implicitly convertible to another type.common_with
- specifies that two types share a common type.integral
- specifies that a type is an integral type.default_constructible
- specifies that an object of a type can be default-constructed.
Comparison concepts:
boolean
- specifies that a type can be used in Boolean contexts.equality_comparable
- specifies thatoperator==
is an equivalence relation.
Object concepts:
movable
- specifies that an object of a type can be moved and swapped.copyable
- specifies that an object of a type can be copied, moved, and swapped.semiregular
- specifies that an object of a type can be copied, moved, swapped, and default constructed.regular
- specifies that a type is regular, that is, it is bothsemiregular
andequality_comparable
.
Callable concepts:
invocable
- specifies that a callable type can be invoked with a given set of argument types.predicate
- specifies that a callable type is a Boolean predicate.
See also: concepts.
# Formatting library
Combine the simplicity of printf
with the type-safety of iostream
. Uses braces as placeholders, and supports custom formatting similar to printf-style specifiers.
|
|
To format custom types:
|
|
# Synchronized buffered outputstream
Buffers output operations for the wrapped output stream ensuring synchronization (i.e. no interleaving of output).
|
|
# std::span
A span is a view (i.e. non-owning) of a container providing bounds-checked access to a contiguous group of elements. Since views do not own their elements they are cheap to construct and copy – a simplified way to think about views is they are holding references to their data. As opposed to maintaining a pointer/iterator and length field, a span wraps both of those up in a single object.
Spans can be dynamically-sized or fixed-sized (known as their extent). Fixed-sized spans benefit from bounds-checking.
Span doesn’t propogate const so to construct a read-only span use std::span<const T>
.
Example: using a dynamically-sized span to print integers from various containers.
|
|
Example: a statically-sized span will fail to compile for containers that don’t match the extent of the span.
|
|
# Bit operations
C++20 provides a new <bit>
header which provides some bit operations including popcount.
|
|
# Math constants
Mathematical constants including PI, Euler’s number, etc. defined in the <numbers>
header.
|
|
# std::is_constant_evaluated
Predicate function which is truthy when it is called in a compile-time context.
|
|
# std::make_shared supports arrays
|
|
# starts_with and ends_with on strings
Strings (and string views) now have the starts_with
and ends_with
member functions to check if a string starts or ends with the given string.
|
|
# Check if associative container has element
Associative containers such as sets and maps have a contains
member function, which can be used instead of the “find and check end of iterator” idiom.
|
|
# std::bit_cast
A safer way to reinterpret an object from one type to another.
|
|
# std::midpoint
Calculate the midpoint of two integers safely (without overflow).
|
|
# std::to_array
Converts the given array/“array-like” object to a std::array
.
|
|
# std::bind_front
Binds the first N arguments (where N is the number of arguments after the given function to std::bind_front
) to a given free function, lambda, or member function.
|
|
# Uniform container erasure
Provides std::erase
and/or std::erase_if
for a variety of STL containers such as string, list, vector, map, etc.
For erasing by value use std::erase
, or to specify a predicate when to erase elements use std::erase_if
. Both functions return the number of erased elements.
|
|
# Three-way comparison helpers
Helper functions for giving names to comparison results:
|
|
See also: three-way comparison.
# std::lexicographical_compare_three_way
Lexicographically compares two ranges using three-way comparison and produces a result of the strongest applicable comparison category type.
|
|
See also: three-way comparison, three-way comparison helpers.
# Acknowledgements
- cppreference - especially useful for finding examples and documentation of new library features.
- C++ Rvalue References Explained - a great introduction I used to understand rvalue references, perfect forwarding, and move semantics.
- clang and gcc’s standards support pages. Also included here are the proposals for language/library features that I used to help find a description of, what it’s meant to fix, and some examples.
- Compiler explorer
- Scott Meyers’ Effective Modern C++ - highly recommended book!
- Jason Turner’s C++ Weekly - nice collection of C++-related videos.
- What can I do with a moved-from object?
- What are some uses of decltype(auto)?
- And many more SO posts I’m forgetting…
# COPYING & ATTRIBUTIONS:
Author Anthony Calandra
Content Contributors
See: https://github.com/AnthonyCalandra/modern-cpp-features/graphs/contributors
License: The MIT License (MIT) Copyright (c) 2024 Anthony Calandra
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.