C++ 20 Features

Coroutines

Coroutines are special functions that can have their execution suspended and resumed. To define a coroutine, the co_returnco_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.

task<> tcp_echo_server()
{
    char data[1024];
    while (true)
    {
        std::size_t n = co_await socket.async_read_some(buffer(data));
        co_await async_write(socket, buffer(data, n));
    }
}

Designated initializers

struct A {
  int x;
  int y;
  int z = 123;
};

A a {.x = 1, .z = 2}; // a.x == 1, a.y == 0, a.z == 2

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.

std::format("{1} {0}", "world", "hello"); // == "hello world"

int x = 123;
std::string str = std::format("x: {}", x); // str == "x: 123"

// Format to an output iterator:
for (auto x : {1, 2, 3}) {
  std::format_to(std::ostream_iterator<char>{std::cout, "\n"}, "{}", x);
}

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.

Span doesn’t propogate const so to construct a read-only span use std::span<const T>.

void print_ints(std::span<const int> ints) {
    for (const auto n : ints) {
        std::cout << n << std::endl;
    }
}

print_ints(std::vector{ 1, 2, 3 });
print_ints(std::array<int, 5>{ 1, 2, 3, 4, 5 });

int a[10] = { 0 };
print_ints(a);
// etc.

Leave a Reply

Your email address will not be published. Required fields are marked *