Reader small image

You're reading from  Modern C++ Programming Cookbook - Third Edition

Product typeBook
Published inFeb 2024
PublisherPackt
ISBN-139781835080542
Edition3rd Edition
Right arrow
Author (1)
Marius Bancila
Marius Bancila
author image
Marius Bancila

Marius Bancila is a software engineer with two decades of experience in developing solutions for line of business applications and more. He is the author of The Modern C++ Challenge and Template Metaprogramming with C++. He works as a software architect and is focused on Microsoft technologies, mainly developing desktop applications with C++ and C#. He is passionate about sharing his technical expertise with others and, for that reason, he has been recognized as a Microsoft MVP for C++ and later developer technologies since 2006. Marius lives in Romania and is active in various online communities.
Read more about Marius Bancila

Right arrow

Preface

C++ is one of the most popular and widely used programming languages, and it has been that way for three decades. Designed with a focus on performance, efficiency, and flexibility, C++ combines paradigms such as object-oriented, imperative, generic, and functional programming. C++ is standardized by the International Organization for Standardization (ISO) and has undergone massive changes over the last decade and a half. With the standardization of C++11, the language has entered a new age, which has been widely referred to as modern C++. Type inference, move semantics, lambda expressions, smart pointers, uniform initialization, variadic templates, and many other recent features have changed the way we write code in C++ to the point that it almost looks like a new programming language. This change has been further advanced with the release of C++20, which includes many new changes to the language, such as modules, concepts, and coroutines, as well as changes to the standard library, such as ranges, text formatting, and calendars. And now, the language is moving even further with more changes introduced in C++23 and the upcoming C++26.

This book addresses many of the new features included in C++11, C++14, C++17, C++20, and C++23. This book is organized into recipes, each covering one particular language or library feature, or a common problem that developers often face and the typical solution to it using modern C++. Through more than 150 recipes, you will learn to master both core language features and the standard libraries; including those for strings, containers, algorithms, iterators, streams, regular expressions, threads, filesystem, atomic operations, utilities, and ranges.

This third edition of the book took several months to write, and during this time the work on the C++23 standard has been completed. However, at the time of writing this preface, the standard is yet to be approved and will be published this year (2024).

More than 30 new or updated recipes in the second and third editions cover C++20 features, including modules, concepts, coroutines, ranges, threads and synchronization mechanisms, text formatting, calendars and time zones, immediate functions, the three-way comparison operator, and the new std::span class. Almost 20 new or updated recipes in this third edition cover C++23 features, including the std::expected class, the std::mdspan class, the stacktrace library, the span buffer, the multi-dimensional subscript operator, and the additions to the text format library.

All the recipes in the book contain code samples that show you how to use a feature or how to solve a problem. These code samples have been written using Visual Studio 2022, but have also been compiled using Clang and GCC. Since the support for various language and library features has been gradually added to all these compilers, it is recommended that you use the latest version of each to ensure that all of the new features are supported.

At the time of writing this preface, the latest versions are GCC 14.0, Clang 18.0, and VC++ 2022 version 14.37 (from Visual Studio 2019 version 17.7). Although all these compilers are C++17 complete, the support for C++23 varies from compiler to compiler. Please refer to https://en.cppreference.com/w/cpp/compiler_support to check your compiler’s support for C++23 features.

Who this book is for

This book is intended for all C++ developers, regardless of their experience level. The typical reader is an entry- or medium-level C++ developer who wants to master the language and become a prolific modern C++ developer. The experienced C++ developer will find a good reference for many C++11, C++14, C++17, C++20, and C++23 language and library features that may come in handy from time to time. The book consists of more than 150 recipes that span simple, to intermediate, and even advanced. However, they all require prior knowledge of C++, and that includes functions, classes, templates, namespaces, macros, and others. Therefore, if you are not familiar with the language, it is recommended that you first read an introductory book to familiarize yourself with the core aspects, and then proceed with this book.

What this book covers

Chapter 1, Learning Modern Core Language Features, teaches you about modern core language features, including type inference, uniform initialization, scoped enumerations, range-based for loops, structured bindings, class template argument deduction, and others.

Chapter 2, Working with Numbers and Strings, discusses how to convert between numbers and strings, generate pseudo-random numbers, work with regular expressions and various types of string, as well as how to format text using the C++20 text formatting library.

Chapter 3, Exploring Functions, dives into defaulted and deleted functions, variadic templates, lambda expressions, and higher-order functions.

Chapter 4, Preprocessing and Compilation, takes a look at various aspects of compilation, from how to perform conditional compilation, to compile-time assertions, code generation, and hinting the compiler with attributes.

Chapter 5, Standard Library Containers, Algorithms, and Iterators, introduces you to several standard containers, many algorithms, and teaches you how to write your own random-access iterator.

Chapter 6, General-Purpose Utilities, dives into the chrono library, including the C++20 calendars and time zones support; the any, optional, variant, and span and mdspan types; and type traits.

Chapter 7, Working with Files and Streams, explains how to read and write data to/from streams, use I/O manipulators to control streams, and explores the filesystem library.

Chapter 8, Leveraging Threading and Concurrency, teaches you how to work with threads, mutexes, locks, condition variables, promises, futures, atomic types, as well as the C++20 latches, barriers, and semaphores.

Chapter 9, Robustness and Performance, focuses on exceptions, constant correctness, type casts, smart pointers, and move semantics.

Chapter 10, Implementing Patterns and Idioms, covers various useful patterns and idioms, such as the pimpl idiom, the non-virtual interface idiom, the curiously recurring template pattern, and mixins.

Chapter 11, Exploring Testing Frameworks, gives you a kickstart with three of the most widely used testing frameworks, Boost.Test, Google Test, and Catch2.

Chapter 12, C++20 Core Features, introduces you to the most important new additions to the C++20 standard—modules, concepts, coroutines, and ranges, including updates in C++23.

What’s new in this edition

This section provides a list of new or updated recipes along with a short description of the change.

Chapter 1, Learning Modern Core Language Features:

  • Using scope enumeration: updated with C++23 std::to_underlying and std::is_scoped_enum
  • Using range-based for loops to iterate on a range: updated with the C++23 init statement
  • Using the subscript operator to access elements in a collection: (new) C++23 multidimensional subscript operator

Chapter 2, Working with Numbers and Strings:

  • Understanding the various numeric types: (new) explains the C++ numerical types
  • Understanding the various character and string types: (new) explains the C++ character types
  • Printing Unicode characters to the output console: (new) discusses working with UNICODE and printing to the console
  • Creating a library of string helpers: updated with C++20 starts_with(), ends_with(), and contains()
  • Formatting and printing text with std::format and std::print: updated with C++23 std::print() and std::println()
  • Using std::format with user-defined types: updated with C++23 std::formattable and better examples

Chapter 3, Exploring Functions:

  • Using lambdas with standard algorithms: updated with C++23 attributes on function call operators
  • Writing a recursive lambda: updated with C++14 recursive generic lambdas
  • Writing function templates: (new) a walkthrough of writing function templates

Chapter 4, Preprocessing and Compilation:

  • Conditionally compiling your source code: updated with C++23 #warning, #elifdef, and #elifndef
  • Performing compile time assertion checks with static_assert: updated with C++26 user-generated messages
  • Providing metadata to the compiler with attributes: updated with C++23 attributes on lambda, [[assume]], and duplicate attributes

Chapter 5, Standard Library Containers, Algorithms, and Iterators:

  • Using vector as default container: updated with C++23 range-aware member functions
  • Selecting the right standard containers (new) a comparison of standard containers

Chapter 6, General-Purpose Utilities:

  • Working with calendars: updated with C++20-compliant examples
  • Converting times between timezones: updated with C++20-compliant examples
  • Chaining together computations which may or may not produce a value: (new) discusses the C++23 std::optional monadic operations
  • Using std::expected for returning a value or an error: (new) discusses the C++23 std::expected type
  • Using std::mdspan for multidimensional views of sequences of objects: (new) explores the C++23 std::mdspan type
  • Providing logging details with source_location: (new) explores the C++20 std::source_location type
  • Using the stacktrace library to print the call stack: (new) teaches the C++23 stacktrace library

Chapter 7, Working with Files and Streams:

  • Using streams on fixed-size external buffers: (new) explores the C++23 span buffers

Chapter 8, Leveraging Threading and Concurrency:

  • Using thread synchronization mechanisms: updated with C++20-compliant samples
  • Synchronizing output streams: (new) discusses the C++20 sync streams

Chapter 9, Robustness and Performance:

  • Creating compile-time constant expressions: updated with C++23 static constexpr variables
  • Optimizing code in constant-evaluated contexts: (new) explains the C++23 if consteval
  • Using virtual function calls in constant expressions: (new) discusses the C++20 constexpr virtual functions

Chapter 10, Implementing Patterns and Idioms:

  • Adding functionality to classes with mixins: (new) explains the mixins pattern
  • Handling unrelated types generically with type erasure: (new) discusses the type erasure idiom

Chapter 11, Exploring Testing Frameworks:

  • Getting started with Catch2: updated installation instructions for Catch2 version 3.4.0
  • Asserting with Catch2: updated examples for Catch2 version 3.4.0

Chapter 12, C++20 Core Features:

  • Exploring abbreviated function templates: (new) examines C++20 abbreviated function templates
  • Exploring the standard range adaptors: (new) discusses the C++20 and C++23 range adaptors
  • Converting a range to a container: (new) explains how to convert a range to a standard container using C++23 std::ranges::to()
  • Using constrained algorithms: (new) explores the general-purpose algorithms that work directly with ranges
  • Creating a coroutine task for asynchronous computation: updated with standard compliant examples (and alternatives with the libcoro library)
  • Creating a coroutine generator type for sequences of values: updated with standard compliant examples (and alternatives with the libcoro library)
  • Recursively generating values with the std::generator type: (new) explains the C++23 std::generator

To get the most out of this book

The code presented in the book is available for download from https://github.com/PacktPublishing/Modern-Cpp-Programming-Cookbook-Third-Edition, although I encourage you to try writing all the samples by yourself. In order to compile them, you need VC++ 2022 17.7 on Windows and GCC 14.0 or Clang 18.0 on Linux and Mac. If you don’t have the latest version of the compiler, or you want to try another compiler, you can use one that is available online.

Although there are various online platforms that you could use, I recommend Wandbox, available at https://wandbox.org/, and Compiler Explorer, available at https://godbolt.org/.

Download the example code files

The code bundle for the book is hosted on GitHub at https://github.com/PacktPublishing/Modern-Cpp-Programming-Cookbook-Third-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/gbp/9781835080542.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: “The geometry module was defined in a file called geometry.ixx/.cppm, although any file name would have had the same result.”

A block of code is set as follows:

static std::map<
  std::string,
  std::function<std::unique_ptr<Image>()>> mapping
{
  { "bmp", []() {return std::make_unique<BitmapImage>(); } },
  { "png", []() {return std::make_unique<PngImage>(); } },
  { "jpg", []() {return std::make_unique<JpgImage>(); } }
};

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are highlighted:

static std::map<
  std::string,
  std::function<std::unique_ptr<Image>()>> mapping
{
  { "bmp", []() {return std::make_unique<BitmapImage>(); } },
  { "png", []() {return std::make_unique<PngImage>(); } },
  { "jpg", []() {return std::make_unique<JpgImage>(); } }
};

Any command-line input or output is written as follows:

running thread 140296854550272
running thread 140296846157568
running thread 140296837764864

Bold: Indicates a new term, an important word, or words that you see on the screen, for example, in menus or dialog boxes, also appear in the text like this. For example: “Select System info from the Administration panel.”

Warnings or important notes appear like this.

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email feedback@packtpub.com, and mention the book’s title in the subject of your message. If you have questions about any aspect of this book, please email us at questions@packtpub.com.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book we would be grateful if you would report this to us. Please visit, http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packtpub.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

Share your thoughts

Once you’ve read Modern C++ Programming Cookbook, Third Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application. 

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

  1. Scan the QR code or visit the link below
Qr code

Description automatically generated

https://packt.link/free-ebook/9781835080542

  1. Submit your proof of purchase
  2. That’s it! We’ll send your free PDF and other benefits to your email directly
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Modern C++ Programming Cookbook - Third Edition
Published in: Feb 2024Publisher: PacktISBN-13: 9781835080542
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Marius Bancila

Marius Bancila is a software engineer with two decades of experience in developing solutions for line of business applications and more. He is the author of The Modern C++ Challenge and Template Metaprogramming with C++. He works as a software architect and is focused on Microsoft technologies, mainly developing desktop applications with C++ and C#. He is passionate about sharing his technical expertise with others and, for that reason, he has been recognized as a Microsoft MVP for C++ and later developer technologies since 2006. Marius lives in Romania and is active in various online communities.
Read more about Marius Bancila