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

Next BeCPP UG Meeting Planned For June 24th, 2021

The next meeting of the Belgian C++ Users Group is planned for Thursday June 24th, 2021 at 18:00 and will be held online through Microsoft Teams.

The agenda is as follows:

  • 18:00: The Teams meeting will start to give people plenty of time to join.
  • 18:30: Session 1: A new way of formatting in C++20, are we getting there in the end? (Lieven de Cock)
    We will have a look at the problems the (s)printf family has brought upon us for decades, how iostreams tries to solve this in an unfriendly way, and how we can now have the best of both worlds, with the upcoming C++20 std::format (or for now with the reference implementation fmt::format).
  • 19:30: Session 2: Understanding value categories in C++ (Kris van Rens)
    In C++ today, do you know what an xvalue is? Or a prvalue? Why would you want to know? Because it matters! In C++, each expression is characterized by a value category. These value categories are used to describe parts of the C++ standard, and are often used in books and articles. You might have heard of terms like ‘lvalue’ or ‘rvalue’, which are the most commonly known ones. Over the years, changes to the C++ language changed the meaning of value categories. This means a lot of information about value categories is outdated or just plain wrong. In this talk, I will explain what expression value categories are in today’s C++ standard. It turns out that knowledge about value categories can really be beneficial. Not only will it enrich your understanding of C++ in general, it will deepen your understanding of mechanisms like move semantics. Also, it can help you to make better choices about code. These choices can then leverage language rules to enable compilers to generate efficient code without redundant copies. Other, related topics that will be covered: copy elision, return value optimization, temporary materialization.

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

There are 300 seats available for this event.

Note: The deadline for registrations is June 23rd, 2021!

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

C++ Extension for Visual Studio Code Reaches 1.0

Visual Studio Code is a free highly-customizable code editor that runs on Linux, macOS, and Windows. The C++ extension brings a rich set of productivity features to VS Code for C++ developers, including IntelliSense smart code completion, debugging, refactoring, code navigation, and more! On top of that, these features are adaptable to various platforms, architectures and compilers, enabling all your cross-compiling and remote development scenarios.

Editing

For editing, the C++ extension brings, among others, IntelliSense, code navigation, refactoring support, code formatting, semantic colorization, …

Debugging

For debugging, the extension brings support for breakpoints, watch variables, stepping through code, debugging multi-threaded applications, debugging remote processes, …

More information can be found here.

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

Pure Virtual C++2020 Conference

Pure Virtual C++
2020

Pure Virtual C++ 2020 is a free single-track one-day virtual conference for the whole C++ community. It is taking place on Thursday 30th April 2020 from 14:30 to 23:00 UTC. Sign up on the event website.

All talks will be pre-recorded and streamed on YouTube Live with a live Q&A session with the speakers. After the event, the talks will be available to watch online for free.

The Pure Virtual C++ conference organized by Microsoft will be run under the Berlin Code of Conduct.

The preliminary schedule is (all times UTC):

  • 14:30-15:30 – Dynamic Polymorphism with Metaclasses and Code Injection by Sy Brand
  • 16:00-16:30 – Optimize Your C++ Development While Working From Home by Nick Uhlenhuth
  • 16:30-17:00 – C++ Cross-Platform Development with Visual Studio and WSL by Erika Sweet
  • 17:30-18:30 – Lucky 7 – Designing Text Encodings for C++ by JeanHeyd Meneide
  • 19:00-20:00 – C++ Development with Visual Studio Code by Julia Reid
  • 20:30-21:00 – Peeking Safely at a Table with Concepts by Gabriel Dos Reis
  • 21:00-21:30 – Practical C++20 Modules and the Future of Tooling Around C++ Modules by Cameron DaCamara
  • 22:00-23:00 – Update on MSVC’s implementation of the C++20 Standard Library by Mahmoud Saleh

Register here!

Share

Next BeCPP UG Meeting Planned For March 30th, 2020

This event is cancelled in light of the current state of the Covid-19 outbreak.
We will try to get our two international speakers, Greg and DeWang, back to Belgium at a future event.

The next meeting of the Belgian C++ Users Group is planned for Monday March 30th, 2020 at 18:00 at KU Leuven Department of Computer Science. The welcoming and reception takes place at Foyer Computerwetenschappen (room 00.191), while the sessions will take place in Auditorium Erik Duval (room 00.225)

Dekimo ( https://www.dekimo.com/ ) and KU Leuven Department of Computer Science ( https://wms.cs.kuleuven.be/cs/english ) are sponsoring this event by providing the location, drinks and catering.

Dekimo Logo
KU LeuvenLogo

This time we have two international speakers:

The agenda is as follows:

  • 18:00: Reception with food.
  • 18:30: Session 1: Amazing tricks with the GDB debugger (Greg Law)
    If you’re writing C++ for anything other than Windows, chances are that you occasionally break out GDB. This session presents some of the lesser known features of GDB that can change the way you debug. GDB has come a long way in the last few years and now does so much more than break, print, step and continue. Reversible debugging; Non-Stop Mode; Multi-process Debugging; and Dynamic Printf are but some of its best features, and its built-in Python scripting is particularly powerful. Join Undo co-founder and CEO, Greg Law, as he takes you through a series of demos to show some amazing tricks with GDB and some of its powerful new (and not-so-new) features that you may not have heard of.
  • 19:15: Session 2: Static analysis and Coverity (DeWang Li)
    The C/C++ code you create plays such a pivotal role on our planet, and as such, companies are investing heavily into ensuring they are safe and robust. One of the disciplines they invest in to ensure that is static analysis. DeWang will explain the fundamentals of static analysis, and using his favorite product, Coverity, demonstrate some of its capabilities. He will share stories from working with some of the top Silicon Valley companies and how they apply Coverity.
  • 19:55: Break
  • 20:10: Session 3: Interactive discussion on pointers (Lieven de Cock)
    Let’s have an exchange of thoughts on the topic of pointers: raw pointers, smart pointers, std/boost::optional and std::reference_wrapper.
    How to express intent and how to avoid checking things that might not be needed to check?
    We will present some use cases to get the discussion going. This is an interactive session, so start thinking about questions or opinions you might have.
  • 20:50: Introduction to Dekimo, and KU Leuven Department of Computer Science, followed by a drink.
C++17 Standard Library Quick Reference


We will give away a copy of C++17 Standard Library Quick Reference.

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

There are 100 seats available for this event.

Note: The deadline for registrations is March 26th, 2020!

Share

Slides of my CodeMonsters 2019 Presentation “Writing Modern C++ Code”

On December 10th, 2019 I gave a presentation titled “Writing Modern C++ Code” at CodeMonsters.
The slides of my presentation can be downloaded below:

Share

Next BeCPP UG Meeting Planned For January 29th, 2020

The next meeting of the Belgian C++ Users Group is planned for Wednesday January 29th, 2020 at 18:00 at OMP.

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

OMP Logo

The agenda is as follows:

  • 18:00: Reception with food.
  • 18:30: Session 1: Coroutines in C++20 (Johan Vanslembrouck)
    A coroutine is a function that can suspend execution to be resumed later. Coroutines allow for sequential code that executes asynchronously (e.g. to handle non-blocking I/O without explicit callbacks), and also supports algorithms on lazy-computed infinite sequences and other uses. Unlike most other languages that support coroutines, C++ coroutines are open and not tied to any particular runtime or generator type and allow libraries to imbue coroutines with meaning, whereas the compiler is responsible solely for efficient transformation of a function to a state machine that is the foundation of the coroutine.
    The presentation will explain the C++ coroutines mechanism, i.e. code generated by the compiler and the code to be written by a coroutine developer. The presentation includes examples of an client-server application using Boost ASIO in combination with C++ 20 coroutines and a producer-consumer queue implemented with and without coroutines.
  • 19:30: Break
  • 19:45: Session 2: The evolution of the C++ Lambda (Lieven de Cock)
    Before C++11, we had to write function objects (functors) or free standing functions to pass as the callable to several algorithms (for example: for_each). The drawback was that we were introducing objects in a bigger scope than actually needed, and it can be considered as rather some boilerplate.
    With the introduction of the lambda we can write (little) callables at the moment we need them. Over the years (or better said over the new standards) the lambdas gained extra power and became more user friendly. In this talk we will have a look on the evolution of the lambda since its birth in C++11.
  • 20:45: Introduction to OMP, followed by a drink.
Professional C++, 4th Edition


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

C++17 Standard Library Quick Reference


We will also give away a copy of C++17 Standard Library Quick Reference.

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

There are 100 seats available for this event.

Note: The deadline for registrations is January 26th, 2020!

Share