Tag Archive for C++20

Next BeCPP UG Meeting Planned For June 28th, 2022

After a long break due to the Corona pandemic, I’m happy to announce that the next meeting of the Belgian C++ Users Group is planned for Tuesday June 28th, 2022 at 18:00 at Vandewiele Experience Center.

Vandewiele ( https://www.vandewiele.com/ ) is sponsoring this event by providing the location, drinks and catering.

Vandewiele Logo

The agenda is as follows:

  • 18:00: Reception with food.
  • 18:30: Session 1: Minimal Logging Framework in C++ 20 (Koen Poppe)
    As developers, adding log statements seems easy and risk-free. However, with hundreds of machines, collecting those log files can become quite a challenge, let alone making sense of the important information they contain. We set out to reduce logging to its essentials and explore optimisations not only in terms of disk space, but also runtime performance and even exposure. Leveraging ideas from well-known software related workflows, we will write a C++20 logging framework from scratch and highlight some surprises along the way.
  • 19:30: Break
  • 19:45: Session 2: Modern CMake (Lieven de Cock)
    CMake is a cross-platform open source software for managing the build process in a portable fashion. We will have a look at the basics of modern CMake. The old, pre modern cmake way should be considered obsolete, for very good reasons. We will talk about targets, build types, dependencies, usage specifications, …, a quick look on cross compilation, and using 3rd party libraries.
  • 20:45: Introduction to Vandewiele, followed by a drink.

Professional C++, 5th Edition
We will be giving away 2 copies of Professional C++, 5th Edition.

The event is free for everyone, but you need to register for it.

There are 30 seats available for this event.

Note: The deadline for registrations is June 22th, 2022!

Share

Microsoft Visual C++ STL is C++20 Feature Complete

Microsoft just announced that their STL included with Visual C++ is now C++20 feature complete. This is the case for:

  • Visual Studio 2022 version 17.2
  • Visual Studio 2019 version 16.11.14

All C++20 features are now available under the /std:c++20 compiler flag.

You can read the full announcement here.

Share

C++20: enum class and using Declarations

C++11 has given use strongly-typed enumeration types which are recommended to be used over the old style enumeration types. The problem with the latter is that the enumerators of such old-style enumeration types are automatically exported into the enclosing scope. This can cause naming collisions with names already defined in the enclosing scope. This is also the reason why enumerators of such types are often prefixed with some label to try to make sure they are unique. For example:

enum Color { ColorRed, ColorGreen, ColorBlue };

The strongly-typed enumeration types from C++11 do not automatically export their enumerators to the enclosing scope.

Let’s look at an example. The following defines and uses a strongly-type enumeration type called Color:

enum class Color { Red, Green, Blue };
Color someColor = Color::Green;

To use the enumerators of the Color enumeration type, you need to fully qualify them with Color::. This can become a bit cumbersome if you, for example, need to have a switch statement on the different enumerators:

switch (someColor) {
    case Color::Red:
        // ...
        break;
    case Color::Green:
        // ...
        break;
    case Color::Blue:
        // ...
        break;
}

Since C++20, you can use a using declaration to avoid having to fully qualify all the different enumerators in the switch cases:

switch (someColor) {
    using enum Color;

    case Red:
        // ...
        break;
    case Green:
        // ...
        break;
    case Blue:
        // ...
        break;
}

Of course, it is recommended to have the scope of the using declaration as small as possible, otherwise you again introduce the risk of having naming collisions. That’s why the using declaration in the earlier example is inside the scope of the switch statement.

My book, Professional C++, 5th Edition, explains all new C++20 features, and much more.

Share

Recording of my CppCon 2021 Session “A Crash Course in Calendars, Dates, Time, and Time Zones”

On October 27th, 2021 I gave a presentation titled “A Crash Course in Calendars, Dates, Time, and Time Zones” at CppCon 2021.
You can find the slides here.

The official video is now also available on YouTube. Enjoy 🙂

Share

C++20: Templated Lambda Expressions

Templated lambda expressions allow you to get easy access to type information of generic lambda expression parameters. This also allows you to put constraints on the types of generic lambda expressions parameters. For example, the following generic lambda expression accepts two parameters, both defined with auto type deduction:

[](const auto& a, const auto& b) { /* ... */ }

Since both parameters are auto type deduced, the compiler is free to choose different types for both parameters. If you do not want this, you can use the following templated lambda expression:

[]<typename T>(const T& a, const T& b) { /* ... */ }

This can be combined with C++20 concepts to further constrain type T. For example, you can require that type T is an integral type as follows (needs <concepts>):

[]<std::integral T>(const T& a, const T& b) { /* ... */ }

Using a templated lambda expression, you have direct access to the type of a parameter. Hence, it’s easier to, for example, create a local variable in your lambda expression that has the same type as the type of one of the parameters. Without a templated lambda expression, you would have to involve decltype() and std::decay_t on generic lambda expression parameters to achieve the same thing.

For example, suppose you have a lambda expression accepting a std::vector where the type of the elements can be anything. We can use a generic lambda expression for this. However, if in the body of the lambda, you want to know the exact type of the elements in the vector, you need to use decltype() and decay_t:

[](const auto& v) {
	using V = std::decay_t<decltype(v)>; // vector's type
	using T = typename V::value_type;    // vector element's type
	T temp;
	/* ... */
}

With a templated lambda expression you can make this much more concise and easier to understand:

[]<typename T>(const std::vector<T>& v) {
	T temp;
	/* ... */
}

My book, Professional C++, 5th Edition, explains all new C++20 features, and much more.

Share

C++20: std::span – A View on a Continuous Sequence of Data

std::span, defined in <span>, allows you to handle a sequence of continuous data, without having to worry about where the data is actually stored. For example, suppose you have a function to print the elements of a std::vector:

void print(const std::vector<int>& values)
{
    for (const auto& value : values) { std::cout << value << " "; }
    std::cout << std::endl;
}

This function requires as argument a reference to a std::vector<int>. If you also want to print elements of a C-style array, then you can add a second overload of the print() function, for example:

void print(const int values[], size_t count)
{
    for (size_t i{ 0 }; i < count; ++i) { std::cout << values[i] << " "; }
    std::cout << std::endl;
}

With these two overloads, you can call your print() function with either a reference to a std::vector<int> or with a C-style array. If you want to support other containers, then you can add even more overloads. With std::span, it is possible to write a single function that can work with all kinds of sequential data. Instead of the previous two overloads, you can just write the following single function:

void print(std::span<const int> values)
{
    for (const auto& value : values) { std::cout << value << " "; }
    std::cout << std::endl;
}

Note that a span basically just contains a pointer to the first element in the sequence and the number of elements in the sequence, and never copies the underlying data. Hence, a span is very cheap to copy and is usually passed by value, just as std::string_view.

This single print() function accepting a std::span can be called for continuous data stored in std::vectors, std::arrays, C-style arrays, and more. Here are some examples:

std::vector v{ 1, 2, 3 };
print(v);                   // Pass a vector.

std::array a{ 4, 5, 6, 7 };
print(a);                   // Pass a std::array.
print({ a.data() + 1, 2 }); // Pass part of a std::array.

int ca[]{ 8, 9, 10 };
print(ca);                  // Pass a C-style array.

std::span s{ v };           // Construct a span from a vector.
print(s);                   // Pass a std::span.
print(s.subspan(1, 2));     // Pass part of a std::span.

The output of this code snippet is as follows:

1 2 3
4 5 6 7
5 6
8 9 10
1 2 3
2 3

Tip: If you write a function accepting a const vector<T>&, I recommend considering to accept a span<const T> instead. This allows your function to work with all kinds of continuous data, independent of where the data is actually stored.


My book, Professional C++, 5th Edition, explains all new C++20 features, and much more.

Share

C++20: Seemingly Unexpected Behavior with Date Arithmetic

C++20 has added support for calendars, dates, and time zones to the C++ Standard Library. This also allows you to perform arithmetic with dates. However, certain arithmetic might give seemingly the wrong results.
Let’s look at a simple example that works as expected:

using namespace std::chrono;
auto timestamp1 = sys_days{ 2022y / January / 19d } + 8h + 39min + 42s;
auto timestamp2 = timestamp1 + days{ 3 }; // Add 3 days
std::cout << timestamp1 << '\n' << timestamp2;

The output is as expected:

2022-01-19 08:39:42
2022-01-22 08:39:42

Now let’s try to add 1 year to timestamp1:

auto timestamp3 = timestamp1 + years{ 1 }; // Add 1 year
std::cout << timestamp1 << '\n' << timestamp3;

The output now is:

2022-01-19 08:39:42
2023-01-19 14:28:54

The date part is correctly incremented with 1 year, but the timestamp looks wrong on first sight. However, this is correct according to the C++ standard. The reason why it is seemingly off has to do with support for leap years. The C++ standard states that adding 1 year to a date must add 1 average year to keep leap years into account. So, while you could expect adding 1 year adds 86,400 * 365 = 31,536,000 seconds (86,400 = number of seconds in a day), it doesn’t. Instead, it adds 86,400 * ((365 * 400) + 97) / 400) = 31,556,952 seconds.

The reason why it is behaving like this is that the type of timestamp1, 2, and 3 is std::chrono::time_point which is a so-called serial type, i.e., it represents a date as a single number relative to a certain epoch (= clock origin). If you don’t want this behavior you can perform the arithmetic with a field-based type. The serial-based types above can be converted to a field-based representation as follows:

// Split timestamp1 into "days" and "remaining seconds".
sys_days timestamp1_days = time_point_cast<days>(timestamp1);
seconds timestamp1_seconds = timestamp1 - timestamp1_days;

// Convert the timestamp1_days serial type to a field-based year_month_day.
year_month_day ymd2 = timestamp1_days;

// Add 1 year.
year_month_day ymd3 = ymd2 + years{ 1 };

// Convert the result back to a serial type.
auto timestamp4 = sys_days{ ymd3 } + timestamp1_seconds;
std::cout << timestamp1 << '\n' << timestamp4;

The output now is:

2022-01-19 08:39:42
2023-01-19 08:39:42
Share

Slides of My Presentation at CppCon 2021

This year at CppCon 2021, I gave the following session:

  • “A Crash Course in Calendars, Dates, Time, and Time Zones”

You can find the slides of the session below.

Share

“Professional C++, 5th Edition” Released

After working on it for a year, I’m proud to announce my new book “Professional C++, 5th Edition” is finished 🙂

It has been updated to the C++20 standard and uses certain C++20 features, such as modules and std::format(), throughout all examples.

It is published by Wiley/Wrox, and available on Amazon.

Official Description

Improve your existing C++ competencies quickly and efficiently with this advanced volume

Professional C++, 5th Edition raises the bar for advanced programming manuals. Complete with a comprehensive overview of the new capabilities of C++20, each feature of the newly updated programming language is explained in detail and with examples. Case studies that include extensive, working code round out the already impressive educational material found within. 

Without a doubt, the new 5th Edition of Professional C++ is the leading resource for dedicated and knowledgeable professionals who desire to advance their skills and improve their abilities. This book contains resources to help readers: 

  • Maximize the capabilities of C++ with effective design solutions  
  • Master little-known elements of the language and learn what to avoid  
  • Adopt new workarounds and testing/debugging best practices  
  • Utilize real-world program segments in your own applications 

Notoriously complex and unforgiving, C++ requires its practitioners to remain abreast of the latest developments and advancements. Professional C++, 5th Edition ensures that its readers will do just that. 

Share

Book “C++ Lambda Story”

A friend of mine published a new book, titled “C++ Lambda Story”. The book explains everything you need to know about lambda expressions in C++.

The book guides you through the evolution of C++ Lambda Expressions so that you can learn it step by step. It starts with C++03 and a motivation to have “ad-hoc” functors, and then moves into the latest C++ standards:

  • C++11 – early days of the feature. You’ll learn about all the essential aspects of lambdas and several tricks you might apply. This is the longest chapter as it needs to cover a lot of topics.
  • C++14 – updates. See how to use generic lambdas and captures with an initializer.
  • C++17 – more improvements, especially by handling ‘this’ pointer and allowing ‘constexpr’. You’ll also learn about the overloaded pattern and how to derive from lambda.
  • C++20 – in this section you’ll see all of the new features adopted for C++20 like template lambdas and how to use them with concepts and constexpr algorithms.

Additionally, throughout the chapters, you’ll learn about the following techniques:

  • Immediately Invoked Functional Expressions (IIFE)
  • How to instrument a default functor to gather extra information
  • Replacing std::bind1st, std::bind2nd and removed functional stuff
  • The Overloaded Pattern and how to inherit from a lambda
  • Passing C++ captureless lambda as a function pointer to C API
  • LIFTING with lambdas
  • Storing lambdas in a container
  • Variadic templates and arguments packs
  • Lambdas and asynchronous execution
  • and many more

The author, Bartłomiej Filipek, is giving a 28% discount to readers of my blog. This offer is valid until 27th of January 2021.
Follow this link to use the coupon if you are interested in this offer.

Share

Book “Beginning C++20”

My friend Peter Van Weert finished a new edition of “Beginning C++20” for which I was technical editor. It’s a great book to learn C++20 for programmers new to C++ and those who may be looking for a refresh primer on C++ in general.

Here is the abstract:

Begin your programming journey with C++ , starting with the basics and progressing through step-by-step examples that will help you become a proficient C++ programmer. This book includes new features from the C++20 standard such as modules, concepts, ranges, and the spaceship operator. All you need are Beginning C++20 and any recent C++ compiler and you’ll soon be writing real C++ programs. There is no assumption of prior programming knowledge.

All language concepts that are explained in the book are illustrated with working program examples, and all chapters include exercises for you to test and practice your knowledge. Free source code downloads are provided for all examples from the text and solutions to the exercises.

This latest edition has been fully updated to the latest version of the language, C++20, and to all conventions and best practices of modern C++. Beginning C++20 also introduces the elements of the C++ Standard Library that provide essential support for the C++20 language.

What You Will Learn:

  • Begin programming with the C++20 standard
  • Carry out modular programming in C++
  • Work with arrays and loops, pointers and references, strings, and more
  • Write your own functions, types, and operators
  • Discover the essentials of object-oriented programming
  • Use overloading, inheritance, virtual functions, and polymorphism
  • Write generic function and class templates, and make them safer using concepts 
  • Learn the ins and outs of containers, algorithms, and ranges
  • Use auto type declarations, exceptions, move semantics, lambda expressions, and much more
Share

Videos of My Presentations at CppCon 2020

This year at CppCon 2020, I gave two sessions:

  • A keynote titled “C++20: An (Almost) Complete Overview”
  • A session titled “C++20 String Formatting Library: An Overview and Use with Custom Types”

You can find the slides here.

The official videos are now also available on YouTube. Enjoy 🙂

Share

Slides of My Presentations at CppCon 2020

This year at CppCon 2020, I gave two sessions:

  • A keynote titled “C++20: An (Almost) Complete Overview”
  • A session titled “C++20 String Formatting Library: An Overview and Use with Custom Types”

You can find the slides of both sessions below.

Share

CppCon 2020 Sessions

I’ll be giving two sessions this year at CppCon 2020:

  • A keynote session titled “C++20: An (Almost) Complete Overview”:
    The technical work on C++20 was finished in January 2020, and is now being pushed through ISO certification.
    This presentation gives an overview of (almost) all new features in both the language and the Standard Library. Some more exotic features will be left out. New language features include modules, coroutines, concepts, templated lambdas, constexpr changes, designated initializers, the spaceship operator, string literals as template parameters, feature test macros, conditional explicit, immediate functions, and more.
    The second part of the session discusses the changes to the Standard Library. This includes topics such as ranges, atomic smart pointers, cancellable threads, a synchronization library, calendars, time zones, span, a formatting library, features test macros, and more.
    The material is mostly the same as the “C++20: What’s in it for you?” session from CppCon 2019, but it has been updated with the final standard. If you want a complete overview of all C++20 features, including references to other more deep-dive sessions at CppCon 2020 on certain topics, then this session is for you.
  • And a session titled “C++20 String Formatting Library: An Overview and Use with Custom Types”:
    C++20 introduced a nice formatting library with std::format(). This session will explain what the formatting library provides, how to use all of its functionality, and most importantly, how you can customize it so that you can use formatting strings that include your very own custom types and custom formatting parameters, and of course, how to handle errors.
Share

CppCon 2020 Keynote

I’m thrilled to announce that I’ll be giving a keynote presentation at this year’s CppCon. Here is the official announcement 😎

The title of my keynote talk is “C++20: An (Almost) Complete Overview”. C++20 is going be discussed quite a bit at this year’s conference and in addition to providing an overview of the new language/library changes, I will guide attendees to other CppCon talks related to C++20.

If you want a complete overview of all C++20 features, including references to other more deep-dive sessions at CppCon 2020 on certain topics, then this session is for you.

After this talk, you should have the confidence and familiarity you need to embrace the latest version of C++.

Part of the abstract:

This presentation gives an overview of (almost) all new features in both the language and the Standard Library. Some more exotic features will be left out. New language features include

  • modules,
  • coroutines,
  • concepts,
  • templated lambdas,
  • constexpr changes,
  • designated initializers,
  • the spaceship operator,
  • string literals as template parameters,
  • feature test macros,
  • conditional explicit,
  • immediate functions,
  • and more.
Share