39,59 €
The updated third edition of Modern C++ Programming Cookbook addresses the latest features of C++23, such as the stacktrace library, std::expected and std::mdspan classes, the header, formatting library improvements, and updates to the ranges library. It also gets into more C++20 topics not previously covered, such as sync streams and source_location.
The book is organized into practical recipes covering a wide range of real-world problems, helping you find the solutions you need quickly. You’ll find coverage of all the core concepts of modern C++ programming and features and techniques from C++11 through to C++23, meaning you’ll stay ahead of the curve by learning to incorporate the newest language and library improvements.
Beyond the core concepts and new features, you’ll explore recipes related to performance and best practices, how to implement useful patterns and idioms, like pimpl, named parameter, attorney-client, and the factory pattern, and how to complete unit testing with the widely used C++ libraries: Boost.Test, Google Test, and Catch2.
With the comprehensive coverage this C++ programming guide offers, by the end of the book you’ll have everything you need to build performant, scalable, and efficient applications in C++.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 1173
Veröffentlichungsjahr: 2024
Modern C++ Programming Cookbook
Third Edition
Master modern C++ including the latest features of C++23 with 140+ practical recipes
Marius Bancila
BIRMINGHAM—MUMBAI
Modern C++ Programming Cookbook
Third Edition
Copyright © 2024 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Senior Publishing Product Manager: Denim Pinto
Acquisition Editor – Peer Reviews: Swaroop Singh
Project Editor: Yamini Bhandari
Senior Development Editor: Elliot Dallow
Copy Editor: Safis Editing
Technical Editor: Aneri Patel
Proofreader: Safis Editing
Indexer: Hemangini Bari
Presentation Designer: Pranit Padwal
Developer Relations Marketing Executive: Vipanshu Parashar
First published: May 2017
Second edition: September 2020
Third edition: February 2024
Production reference: 1260224
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK.
ISBN 978-1-83508-054-2
www.packt.com
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 Template Metaprogramming with C++ and The Modern C++ Challenge. 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.
I would like to thank Denim Pinto, Yamini Bhandari, Elliot Dallow, and all the other people from Packt that have worked on the book for their constant effort, as well as the reviewers, whose feedback only made the book better.
Deák Ferenc got into the world of software development back when programming involved deciphering archaic mnemonics from the pages of magazines and manually typing them into a HC-91 computer. Since then he has become a security and safety-focused software developer, and now has over 20 years of experience in that field. He specializes in low-level system programming, optimization, and application safety analysis. He is well-versed in C and C++, with additional expertise in languages like Go, Java, Python, and others. When not working, he enjoys cooking traditional dishes from Transylvania.
I want to express my gratitude to Packt and the author for including me in this exciting journey and giving me the opportunity to review this book.
Alex Snape has always had a passion for technology, this led him into a career in software development spanning nearly three decades. During his career, Alex has worked across a number of sectors, from video games to financial systems and many things between. He is now working as a software architect in UK public infrastructure.
I would like to thank my parents, my wonderful wife Zoe, and my two adorable children, Aurelia and Marilla.
Join our community’s Discord space for discussions with the author and other readers:
https://discord.gg/7xRaTCeEhx
Preface
Who this book is for
What this book covers
What’s new in this edition
To get the most out of this book
Get in touch
Learning Modern Core Language Features
Using auto whenever possible
How to do it...
How it works...
See also
Creating type aliases and alias templates
How to do it...
How it works...
See also
Understanding uniform initialization
Getting ready
How to do it...
How it works...
There’s more...
See also
Understanding the various forms of non-static member initialization
How to do it...
How it works...
See also
Controlling and querying object alignment
Getting ready
How to do it...
How it works...
See also
Using scoped enumerations
How to do it...
How it works...
See also
Using override and final for virtual methods
Getting ready
How to do it...
How it works...
See also
Using range-based for loops to iterate on a range
Getting ready
How to do it...
How it works...
See also
Enabling range-based for loops for custom types
Getting ready
How to do it...
How it works...
See also
Using explicit constructors and conversion operators to avoid implicit conversion
Getting ready
How to do it...
How it works...
See also
Using unnamed namespaces instead of static globals
Getting ready
How to do it...
How it works...
See also
Using inline namespaces for symbol versioning
Getting ready
How to do it...
How it works...
See also
Using structured bindings to handle multi-return values
Getting ready
How to do it...
How it works...
There’s more...
See also
Simplifying code with class template argument deduction
How to do it...
How it works...
See also
Using the subscript operator to access elements in a collection
How to do it…
How it works…
See also
Working with Numbers and Strings
Understanding the various numeric types
How to do it…
How it works…
See also
Limits and other properties of numeric types
Getting ready
How to do it...
How it works...
See also
Converting between numeric and string types
Getting ready
How to do it...
How it works...
See also
Understanding the various character and string types
How to do it…
How it works…
See also
Printing Unicode characters to the output console
How to do it…
How it works…
See also
Generating pseudo-random numbers
Getting ready
How to do it...
How it works...
See also
Properly initializing a pseudo-random number generator
Getting ready
How to do it...
How it works...
See also
Creating cooked user-defined literals
Getting ready
How to do it...
How it works...
There’s more...
See also
Creating raw user-defined literals
Getting ready
How to do it...
How it works...
See also
Using raw string literals to avoid escaping characters
Getting ready
How to do it...
How it works...
See also
Creating a library of string helpers
Getting ready
How to do it...
How it works...
There’s more…
See also
Verifying the format of a string using regular expressions
Getting ready
How to do it...
How it works...
There’s more...
See also
Parsing the content of a string using regular expressions
Getting ready
How to do it...
How it works...
See also
Replacing the content of a string using regular expressions
Getting ready
How to do it...
How it works...
See also
Using std::string_view instead of constant string references
Getting ready
How to do it...
How it works...
See also
Formatting and printing text with std::format and std::print
Getting ready
How to do it...
How it works...
See also
Using std::format with user-defined types
Getting ready
How to do it...
How it works...
There’s more…
See also
Exploring Functions
Defaulted and deleted functions
Getting started
How to do it...
How it works...
See also
Using lambdas with standard algorithms
Getting ready
How to do it...
How it works...
See also
Using generic and template lambdas
Getting started
How to do it...
How it works...
See also
Writing a recursive lambda
Getting ready
How to do it...
How it works...
See also
Writing function templates
How to do it…
How it works…
See also
Writing a function template with a variable number of arguments
Getting ready
How to do it...
How it works...
See also
Using fold expressions to simplify variadic function templates
Getting ready
How to do it...
How it works...
There’s more...
See also
Implementing the higher-order functions map and fold
Getting ready
How to do it...
How it works...
There’s more...
See also
Composing functions into a higher-order function
Getting ready
How to do it...
How it works...
There’s more...
See also
Uniformly invoking anything callable
Getting ready
How to do it...
How it works...
See also
Preprocessing and Compilation
Conditionally compiling your source code
Getting ready
How to do it...
How it works...
There’s more…
See also
Using the indirection pattern for preprocessor stringification and concatenation
Getting ready
How to do it...
How it works...
See also
Performing compile-time assertion checks with static_assert
Getting ready
How to do it...
How it works...
See also
Conditionally compiling classes and functions with enable_if
Getting ready
How to do it...
How it works...
There’s more...
See also
Selecting branches at compile time with constexpr if
Getting ready
How to do it...
How it works...
See also
Providing metadata to the compiler with attributes
How to do it...
How it works...
See also
Standard Library Containers, Algorithms, and Iterators
Using vector as a default container
Getting ready
How to do it...
How it works...
See also
Using bitset for fixed-size sequences of bits
Getting ready
How to do it...
How it works...
There’s more...
See also
Using vector<bool> for variable-size sequences of bits
Getting ready...
How to do it...
How it works...
There’s more...
See also
Using the bit manipulation utilities
Getting ready
How to do it…
How it works…
See also
Finding elements in a range
Getting ready
How to do it...
How it works...
See also
Sorting a range
Getting ready
How to do it...
How it works...
See also
Initializing a range
Getting ready
How to do it...
How it works...
There’s more…
See also
Using set operations on a range
Getting ready
How to do it...
How it works...
See also
Using iterators to insert new elements into a container
Getting ready
How to do it...
How it works...
There’s more...
See also
Writing your own random-access iterator
Getting ready
How to do it...
How it works...
There’s more...
See also
Container access with non-member functions
Getting ready
How to do it...
How it works...
There’s more...
See also
Selecting the right standard containers
How to do it…
How it works…
See also
General-Purpose Utilities
Expressing time intervals with chrono::duration
Getting ready
How to do it...
How it works...
There’s more...
See also
Working with calendars
Getting ready
How to do it…
How it works…
There’s more…
See also
Converting times between time zones
Getting ready
How to do it…
How it works…
See also
Measuring function execution time with a standard clock
Getting ready
How to do it...
How it works...
See also
Generating hash values for custom types
Getting ready
How to do it...
How it works...
See also
Using std::any to store any value
Getting ready
How to do it...
How it works...
See also
Using std::optional to store optional values
Getting ready
How to do it...
How it works...
There’s more…
See also
Chaining together computations that may or may not produce a value
Getting ready
How to do it…
How it works…
There’s more…
See also
Using std::variant as a type-safe union
Getting ready
How to do it...
How it works...
There’s more...
See also
Visiting a std::variant
Getting ready
How to do it...
How it works...
See also
Using std::expected to return a value or an error
Getting ready
How to do it…
How it works…
See also
Using std::span for contiguous sequences of objects
Getting ready
How to do it…
How it works…
See also
Using std::mdspan for multi-dimensional views of sequences of objects
Getting ready
How to do it…
How it works…
There’s more…
See also
Registering a function to be called when a program exits normally
Getting ready
How to do it...
How it works...
See also
Using type traits to query properties of types
Getting ready
How to do it...
How it works...
There’s more...
See also
Writing your own type traits
Getting ready
How to do it...
How it works...
See also
Using std::conditional to choose between types
Getting ready
How to do it...
How it works...
See also
Providing logging details with source_location
How to do it…
How it works…
See also
Using the stacktrace library to print the call sequence
How to do it…
How it works…
See also
Working with Files and Streams
Reading and writing raw data from/to binary files
Getting ready
How to do it...
How it works...
There’s more...
See also
Reading and writing objects from/to binary files
Getting ready
How to do it...
How it works...
See also
Using streams on fixed-size external buffers
How to do it…
How it works…
See also
Using localized settings for streams
Getting ready
How to do it...
How it works...
See also
Using I/O manipulators to control the output of a stream
Getting ready
How to do it...
How it works...
See also
Using monetary I/O manipulators
Getting ready
How to do it...
How it works...
See also
Using time I/O manipulators
Getting ready
How to do it...
How it works...
See also
Working with filesystem paths
Getting ready
How to do it...
How it works...
See also
Creating, copying, and deleting files and directories
Getting ready
How to do it...
How it works...
See also
Removing content from a file
Getting ready
How to do it...
How it works...
See also
Checking the properties of an existing file or directory
Getting ready
How to do it...
How it works...
See also
Enumerating the content of a directory
Getting ready
How to do it...
How it works...
There’s more...
See also
Finding a file
Getting ready
How to do it...
How it works...
See also
Leveraging Threading and Concurrency
Working with threads
Getting ready
How to do it...
How it works...
See also
Synchronizing access to shared data with mutexes and locks
Getting ready
How to do it...
How it works...
See also
Finding alternatives for recursive mutexes
Getting ready
How to do it...
How it works...
See also
Handling exceptions from thread functions
Getting ready
How to do it...
How it works...
See also
Sending notifications between threads
Getting ready
How to do it...
How it works...
See also
Using promises and futures to return values from threads
Getting ready
How to do it...
How it works...
There’s more...
See also
Executing functions asynchronously
Getting ready
How to do it...
How it works...
See also
Using atomic types
Getting ready
How to do it...
How it works...
See also
Implementing parallel map and fold with threads
Getting ready
How to do it...
How it works...
See also
Implementing parallel map and fold with tasks
Getting ready
How to do it...
How it works...
There’s more...
See also
Implementing parallel map and fold with standard parallel algorithms
Getting ready
How to do it...
How it works...
There’s more...
See also
Using joinable threads and cancellation mechanisms
Getting ready
How to do it...
How it works...
See also
Synchronizing threads with latches, barriers, and semaphores
Getting ready
How to do it...
How it works...
See also
Synchronizing writing to output streams from multiple threads
How to do it…
How it works…
See also
Robustness and Performance
Using exceptions for error handling
Getting ready
How to do it...
How it works...
There’s more...
See also
Using noexcept for functions that do not throw exceptions
How to do it...
How it works...
There’s more...
See also
Ensuring constant correctness for a program
How to do it...
How it works...
There’s more...
See also
Creating compile-time constant expressions
Getting ready
How to do it...
How it works...
There’s more…
See also
Creating immediate functions
How to do it…
How it works…
See also
Optimizing code in constant-evaluated contexts
How to do it…
How it works…
See also
Using virtual function calls in constant expressions
Getting ready
How to do it…
How it works…
See also
Performing correct type casts
How to do it...
How it works...
There’s more...
See also
Implementing move semantics
Getting ready
How to do it...
How it works...
There’s more...
See also
Using unique_ptr to uniquely own a memory resource
Getting ready
How to do it...
How it works...
See also
Using shared_ptr to share a memory resource
Getting ready
How to do it...
How it works...
See also
Consistent comparison with the operator <=>
Getting ready
How to do it…
How it works…
See also
Comparing signed and unsigned integers safely
How to do it…
How it works…
See also
Implementing Patterns and Idioms
Avoiding repetitive if-else statements in factory patterns
Getting ready
How to do it...
How it works...
There’s more...
See also
Implementing the pimpl idiom
Getting ready
How to do it...
How it works...
There’s more...
See also
Implementing the named parameter idiom
Getting ready
How to do it...
How it works...
See also
Separating interfaces and implementations with the non-virtual interface idiom
Getting ready
How to do it...
How it works...
See also
Handling friendship with the attorney-client idiom
Getting ready
How to do it...
How it works...
See also
Static polymorphism with the curiously recurring template pattern
Getting ready
How to do it...
How it works...
There’s more...
See also
Adding functionality to classes with mixins
How to do it…
How it works…
See also
Handling unrelated types generically with the type erasure idiom
Getting ready
How to do it…
How it works…
See also
Implementing a thread-safe singleton
Getting ready
How to do it...
How it works...
There’s more...
See also
Exploring Testing Frameworks
Getting started with Boost.Test
Getting ready
How to do it...
How it works...
There’s more...
See also
Writing and invoking tests with Boost.Test
Getting ready
How to do it...
How it works...
See also
Asserting with Boost.Test
Getting ready
How to do it...
How it works...
See also
Using fixtures in Boost.Test
Getting ready
How to do it...
How it works...
See also
Controlling output with Boost.Test
Getting ready
How to do it...
How it works...
There’s more...
See also
Getting started with Google Test
Getting ready
How to do it...
How it works...
There’s more...
See also
Writing and invoking tests with Google Test
Getting ready
How to do it...
How it works...
See also
Asserting with Google Test
How to do it...
How it works...
See also
Using test fixtures with Google Test
Getting ready
How to do it...
How it works...
See also
Controlling output with Google Test
Getting ready
How to do it...
How it works...
See also
Getting started with Catch2
Getting ready
How to do it...
How it works...
There’s more...
See also
Writing and invoking tests with Catch2
How to do it...
How it works...
See also
Asserting with Catch2
Getting ready
How to do it...
How it works...
See also
Controlling output with Catch2
Getting ready
How to do it…
How it works...
See also
C++ 20 Core Features
Working with modules
Getting ready
How to do it…
How it works...
See also
Understanding module partitions
Getting ready
How to do it...
How it works...
There’s more...
See also
Specifying requirements on template arguments with concepts
Getting ready
How to do it...
How it works...
There’s more...
See also
Using requires expressions and clauses
Getting ready
How to do it...
How it works...
See also
Exploring abbreviated function templates
How to do it…
How it works…
See also
Iterating over collections with the ranges library
Getting ready
How to do it...
How it works...
There’s more...
See also
Exploring the standard range adaptors
Getting ready
How to do it…
How it works…
See also
Converting a range to a container
Getting ready
How to do it…
How it works…
See also
Creating your own range view
Getting ready
How to do it...
How it works...
See also
Using constrained algorithms
How to do it…
How it works…
See also
Creating a coroutine task type for asynchronous computations
Getting ready
How to do it...
How it works...
There’s more...
See also
Creating a coroutine generator type for sequences of values
Getting ready
How to do it...
How it works...
There’s more...
See also
Generating a sequence of values with the std::generator type
How to do it…
How it works…
See also
Other Books You May Enjoy
Index
Cover
Index
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.
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.
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.
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_enumUsing range-based for loops to iterate on a range: updated with the C++23 init statementUsing the subscript operator to access elements in a collection: (new) C++23 multidimensional subscript operatorChapter 2, Working with Numbers and Strings:
Understanding the various numeric types: (new) explains the C++ numerical typesUnderstanding the various character and string types: (new) explains the C++ character typesPrinting Unicode characters to the output console: (new) discusses working with UNICODE and printing to the consoleCreating 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 examplesChapter 3, Exploring Functions:
Using lambdas with standard algorithms: updated with C++23 attributes on function call operatorsWriting a recursive lambda: updated with C++14 recursive generic lambdasWriting function templates: (new) a walkthrough of writing function templatesChapter 4, Preprocessing and Compilation:
Conditionally compiling your source code: updated with C++23 #warning, #elifdef, and #elifndefPerforming compile time assertion checks with static_assert: updated with C++26 user-generated messagesProviding metadata to the compiler with attributes: updated with C++23 attributes on lambda, [[assume]], and duplicate attributesChapter 5, Standard Library Containers, Algorithms, and Iterators:
Using vector as default container: updated with C++23 range-aware member functionsSelecting the right standard containers (new) a comparison of standard containersChapter 6, General-Purpose Utilities:
Working with calendars: updated with C++20-compliant examplesConverting times between timezones: updated with C++20-compliant examplesChaining together computations which may or may not produce a value: (new) discusses the C++23 std::optional monadic operationsUsing std::expected for returning a value or an error: (new) discusses the C++23 std::expected typeUsing std::mdspan for multidimensional views of sequences of objects: (new) explores the C++23 std::mdspan typeProviding logging details with source_location: (new) explores the C++20 std::source_location typeUsing the stacktrace library to print the call stack: (new) teaches the C++23 stacktrace libraryChapter 7, Working with Files and Streams:
Using streams on fixed-size external buffers: (new) explores the C++23 span buffersChapter 8, Leveraging Threading and Concurrency:
Using thread synchronization mechanisms: updated with C++20-compliant samplesSynchronizing output streams: (new) discusses the C++20 sync streamsChapter 9, Robustness and Performance:
Creating compile-time constant expressions: updated with C++23 static constexpr variablesOptimizing code in constant-evaluated contexts: (new) explains the C++23 if constevalUsing virtual function calls in constant expressions: (new) discusses the C++20 constexpr virtual functionsChapter 10, Implementing Patterns and Idioms:
Adding functionality to classes with mixins: (new) explains the mixins patternHandling unrelated types generically with type erasure: (new) discusses the type erasure idiomChapter 11, Exploring Testing Frameworks:
Getting started with Catch2: updated installation instructions for Catch2 version 3.4.0Asserting with Catch2: updated examples for Catch2 version 3.4.0Chapter 12, C++20 Core Features:
Exploring abbreviated function templates: (new) examines C++20 abbreviated function templatesExploring the standard range adaptors: (new) discusses the C++20 and C++23 range adaptorsConverting 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 rangesCreating 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::generatorThe 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/.
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!
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.
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 140296837764864Bold: 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.
Feedback from our readers is always welcome.
General feedback: Email [email protected], 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 [email protected].
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 [email protected] 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.
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.
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:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781835080542
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly