Posts for: #Let's Try C++20

Let’s try C++20 | Range-based for statements with initializer

Thomas Köppe wrote the proposal P0614R1 to describe a new feature called “Range-based for statements with initializer”. This document has been approved as part of the C++20 standard.

The document is pretty straightforward since the feature is quite simple. If you have heard of if statement with initializer from C++17, then you have probably already guessed what “range-based for statements with initializer” means.

To understand this new feature, let’s say we want some code to print all the elements of a collection. The first idea would be to use a range-based for loop. But let’s add another requirement: we want to print the index of the element in the collection. Let’s write some code before and after C++20 and compare them.

Let’s try C++20 | Compare objects

Let’s try C++20 | comparisons

C++20 comes with new possibilities to compare objects.

Let’s start with this simple code where we try to compare 2 objects of user-defined type:

#include <iostream>

struct Foo {
    const int value;
};

int main() {
    Foo a{42};
    Foo b{66};

    std::cout << std::boolalpha;
    std::cout << (a == b) << '\n';
    std::cout << (a != b) << '\n';

    std::cout << (a > b) << '\n';
    std::cout << (a >= b) << '\n';

    std::cout << (a < b) << '\n';
    std::cout << (a <= b) << '\n';
}

This code doesn’t compile, no matter which version of C++ you are using. Indeed, none of these operators are implicitly defined by the compiler and we get 6 errors (one per operator):

Let’s try C++20 | virtual constexpr functions

Once, I wondered if we could have virtual constexpr functions. It is now possible with C++20 so let’s try!

A Piece of Personal Experience

Two years ago, I had several classes with a common point: base classes had a pure virtual function to request derived classes to return a constant. Something like this:

struct Memory {
    // Capacity in bytes
    virtual unsigned int capacity() const = 0;
};

It was the base class for drivers to communicate with a particular memory chip. Each subclass would return the size of the actual memory it handles. For instance, for the Microchip’s 25LC160C EEPROM:

Let’s try C++20 | std::span

Eventually, I have decided to try C++20 😀

Let’s start with std::span!

What is a Span?

Here is the definition given by cppreference:

The class template span describes an object that can refer to a contiguous sequence of objects with the first element of the sequence at position zero.

Spans are sometimes called “views” because they don’t own the sequence of objects.

If you are familiar with std::string_view from C++17, then you can easily understand the concept of spans. std::string_views are somehow spans on sequences of characters. The main difference is that spans can modify the objects while string views can’t modify the characters.