Formatting Text in C++: The Old and The New Ways

When it comes to format a piece of text in C++ there are several ways you can employ: I/O streams, particularly std::stringstream with stream operations (such as operator <<) printf family of functions, particularly sprintf the C++20 format library, particularly std::format / std::format_to any 3rd party library, {fmt} in particular (the source of the new…

requires expressions and requires clauses in C++20

The C++20 standard added constraints and concepts to the language. This addition introduced two new keywords into the language, concept and requires. The former is used to declare a concept, while the latter is used to introduce a requires expression or a requires clause. These two could be confusion at first, so let’s take a…

Writing a simple logging function in C++20

Logging is an important feature of any serious program. In general, one should use established libraries for logging. However, for the sake of showcasing several new features from C++20, now available in Visual Studio 2019 16.10, I will show, in this post, how one can quickly write a simple logging function.

Initializing statement for if/switch/foreach

There are several statements in C++ whose syntax was modified in recent versions of the standard. I refer here to the if and switch statements that were modified in C++17 to include initializing statements, and the range-based for loop that supports the same as of C++20. Their general form is shown in the following table:

Express one of multiple options in a nice way

We often find ourselves writing if statements where a variable is compared with several values either to check if it matches one of them or that it doesn’t match any. Here is an example:

int option = ...;

// at lease a value is matched
if (option == 12 || option == 23 || option == 42)
   std::cout << "it's a good option\n";

// no value is matched
if (option != 12 && option != 23 && option != 42)
   std::cout << "it's a bad option\n";

This example has three comparison values for each case, but it could be 5, or 10, or any number. If it’s too many then perhaps a different approach should be taken. However, the question is, how do we express this in a simpler way in C++, rather than a long if condition?

The little functions that matter

Starting with C++20, some very useful functions for searching have been added to some standard containers, such as std::map, std::set, and std::string. These have been required for a long time and it’s good to see that the committee finally agreed upon their value. I hope this is the beginning of some wonderful additions.

C++20 books

The C++20 standard is complete and is supposed to be published later this year after the voting of the final draft takes place. However, there are books already with C++20 content. In this blog post I present a list of them. The C++ Standard Library, 3rd edition – Rainer Grimm Rainer is an author, consultant,…