skip to content

Which C++23 additions — std::print, std::generator, import std, std::mdspan and std::flat_map — complete what C++20 started, and how?

level: middleimportance: should knowfreq 40%

answer

  1. C++23 fills C++20's gaps
  2. format gets an output function
  3. coroutines get a generator
  4. modules get the standard library
  5. span grows dimensions, map goes contiguous

basics

~20 s

C++23 fills gaps C++20 left: std::print writes std::format output directly, std::generator gives coroutines a standard lazy sequence, import std makes the library importable as a module, std::mdspan adds multidimensional views, and std::flat_map offers a contiguous sorted map.

solid answer

~40 s

C++23 is a completing release. **`std::print` and `std::println`** (`<print>`) write `std::format` output straight to standard output or a stream, without building a string first. **`std::generator<T>`** (`<generator>`) is the coroutine-based lazy sequence C++20 lacked: `co_yield` values and iterate with range-`for`. **`import std;`** and `import std.compat;` make the whole standard library available as named modules. **`std::mdspan`** (`<mdspan>`) extends `std::span` to several dimensions, helped by the C++23 multidimensional subscript `m[i, j]`. **`std::flat_map`** (`<flat_map>`) is a sorted map adaptor over two contiguous containers — `std::vector`s by default — trading slower insertion for cache-friendly lookup and iteration. Support is uneven: Apple clang 21's libc++ has print, mdspan and flat_map but no `std::generator`.

code

cpp · 24 lines
cpp
#include <flat_map>
#include <mdspan>
#include <print>
#include <ranges>
#include <string>
#include <vector>

int main() {
    // std::flat_map: sorted keys and values in two contiguous containers
    std::flat_map<std::string, int> hits{{"/login", 3}, {"/api", 12}};
    hits["/health"] = 40;
    for (const auto& [path, n] : hits) std::println("{} {}", path, n);

    // std::mdspan: a 2-D view over one flat buffer; C++23 allows m[i, j]
    std::vector<double> buf(6);
    std::mdspan grid(buf.data(), 2, 3);
    for (std::size_t i = 0; i < grid.extent(0); ++i)
        for (std::size_t j = 0; j < grid.extent(1); ++j) grid[i, j] = 10.0 * i + j;
    std::println("{}", buf);

    // std::ranges::to: materialize a view into a container
    auto keys = hits.keys() | std::ranges::to<std::vector>();
    std::println("{} keys, first {}", keys.size(), keys.front());
}

go deeper

for a junior

Know that C++23 added std::print and std::println for formatted output and std::expected for errors, and that it builds on C++20.

for a middle

Explain how each addition completes a C++20 feature: print for format, generator for coroutines, import std for modules, mdspan for span.

for a senior

Give flat_map's trade-off against std::map and state which C++23 parts your toolchains really ship, with a fallback for the missing ones.

for a principal

Decide which C++23 additions are worth raising the baseline for, given uneven library support and GCC 16 still calling its C++23 mode experimental.

## A completing release Like C++14 after C++11, **C++23** mostly finishes what the previous large release started. A candidate describing a modernised service can usually tie each C++23 addition to a C++20 feature it completes: | C++20 piece | Gap it left | C++23 completion | |---|---|---| | `std::format` | no way to print without building a `std::string` | `std::print`, `std::println` in `<print>` | | coroutines | no standard generator type | `std::generator` in `<generator>` | | modules | the standard library itself was not importable | `import std;` and `import std.compat;` | | `std::span` | one dimension only | `std::mdspan` in `<mdspan>`, plus `m[i, j]` | | ranges | views could not easily become containers | `std::ranges::to`, `views::zip`, `views::enumerate` | | `std::map` | node-based storage only | `std::flat_map` in `<flat_map>` | ## Printing `std::println("{} requests in {} ms", n, ms)` formats with the same mini-language as `std::format` and writes to standard output, adding a newline. Overloads take a `FILE*` or, from `<ostream>`, a `std::ostream&`. The format string is checked at compile time, and output to a terminal is handled as Unicode text where the platform supports it — one reason it is preferred over `printf`. ## Generators A C++23 generator is a coroutine returning `std::generator<T>`: ```cpp // C++23 <generator>; not available in Apple clang 21's libc++ std::generator<int> ids(int first) { for (int i = first;; ++i) co_yield i; } // for (int id : ids(100) | std::views::take(3)) ... ``` The generator is a lazy input range: each iteration resumes the coroutine until the next `co_yield`. It composes with ranges views. A generator is **move-only** and **single-pass**: once consumed it cannot be restarted, and a reference parameter captured by the coroutine must outlive the whole iteration, not just the call. Library support is the slowest of the C++23 additions: the libc++ status page for LLVM 23 still lists `std::generator` as not implemented, while libstdc++ 16 ships the `<generator>` header. ## The standard library as a module C++20 modules let you write your own modules, but `#include <vector>` was still textual. C++23 defines two named modules: **`std`**, which exports everything in namespace `std`, and **`std.compat`**, which additionally exports the C library's global-namespace names such as `::printf`. Using them requires a compiler and build system that can build the standard library module first, so adoption follows the same tooling curve as modules themselves. ## Multidimensional views and flat containers - **`std::mdspan`** views a flat buffer as a matrix or higher-rank array, with extents fixed at compile time or at run time and a layout policy such as row-major `std::layout_right`. C++23 also lets `operator[]` take several arguments, so `grid[i, j]` replaces `grid(i, j)` or index arithmetic. - **`std::flat_map`** and `std::flat_set` keep keys sorted in contiguous storage. `std::flat_map` holds keys and mapped values in **two separate containers**, `std::vector` by default, so lookups binary-search one dense array. Insertion and erasure in the middle are linear, and iterators are invalidated by insertion, unlike `std::map`. It suits data built once and read often. ## Smaller C++23 additions worth naming C++23 also carries many small, frequently used pieces: - **`std::to_underlying`** converts an enumeration to its underlying integer without spelling the type; - **`std::unreachable`** marks code that cannot be reached, for the optimizer; - `std::string::contains` and `std::string_view::contains`; - **`std::byteswap`** in `<bit>`, and `std::stacktrace` in `<stacktrace>`; - range adaptors `views::zip`, `views::enumerate` and `views::chunk`; - `std::move_only_function`, a `std::function` that accepts move-only callables; - language conveniences: `if consteval`, `static operator()`, the decay-copy `auto(x)`, and the multidimensional subscript used by `std::mdspan`. Each is small, but together they remove a lot of hand-written helpers, and naming one or two you used signals real experience with the revision. ## Support in practice A modernisation story should name the toolchain. Apple clang 21 with libc++, used to check this answer, compiles `std::print`, `std::mdspan`, `std::flat_map` and `std::ranges::to` in `-std=c++23` mode, but has no `<generator>`. GCC 16 documents its C++23 mode as experimental. The honest interview line is therefore: 1. what you used, 2. on which compiler and standard library, 3. and what you had to polyfill or postpone.

  • When would you choose std::flat_map over std::map in a C++23 service?
    When the map is built once or rarely changed and then searched or iterated often: contiguous keys make binary search and iteration cache-friendly and the per-node allocations disappear. Avoid it when inserts and erases in the middle are frequent, because each one shifts elements, or when code relies on `std::map`'s iterator and reference stability across insertion.
  • What is the difference between import std and import std.compat?
    `import std;` exports the C++ standard library's declarations in namespace `std`, including the C library functions as `std::printf` and friends. `import std.compat;` exports everything `std` does plus the C library names in the global namespace, such as `::printf`, for code that calls them unqualified. Neither exports macros, so `assert` or `errno`-style macros still need their headers.

  • std::print is only a renamed printf with the same type rules.
  • std::flat_map is a hash map with better cache behaviour.
  • import std works with any C++23 compiler without build-system support.
  • Every C++23 toolchain already ships std::generator.
  • std::mdspan owns and allocates its multidimensional storage.

Assumes C++23 (ISO/IEC 14882:2024); library availability checked with Apple clang 21 libc++, LLVM 23 status pages and libstdc++ 16 headers.