Modern C++ Programming Cookbook: Master Modern C++ with comprehensive solutions for C++23 and all previous standards. 3 Ed

Modern C++ Programming Cookbook: Master Modern C++ with comprehensive solutions for C++23 and all previous standards. 3 Ed

Modern C++ Programming Cookbook: Master Modern C++ with comprehensive solutions for C++23 and all previous standards. 3 Ed

Автор: Marius Bancila
Дата выхода: 2024
Издательство: Packt Publishing Limited
Количество страниц: 817
Размер файла: 9,6 МБ
Тип файла: PDF
Добавил: codelibs
 Проверить на вирусы  Дополнительные материалы 

Preface xiii
Chapter 1: Learning Modern Core Language Features 1
Using auto whenever possible ................................................................................................... 2
Creating type aliases and alias templates ................................................................................... 7
Understanding uniform initialization ........................................................................................ 9
Understanding the various forms of non-static member initialization ......................................... 15
Controlling and querying object alignment ............................................................................. 20
Using scoped enumerations .................................................................................................... 25
Using override and final for virtual methods ........................................................................... 30
Using range-based for loops to iterate on a range ..................................................................... 33
Enabling range-based for loops for custom types ..................................................................... 38
Using explicit constructors and conversion operators to avoid implicit conversion ......................... 42
Using unnamed namespaces instead of static globals ............................................................... 47
Using inline namespaces for symbol versioning ...................................................................... 50
Using structured bindings to handle multi-return values ......................................................... 53
Simplifying code with class template argument deduction ....................................................... 58
Using the subscript operator to access elements in a collection ................................................ 62
Chapter 2: Working with Numbers and Strings 69
Understanding the various numeric types ............................................................................... 70
Limits and other properties of numeric types .......................................................................... 75
Converting between numeric and string types ......................................................................... 79
Understanding the various character and string types ............................................................. 83
Printing Unicode characters to the output console ................................................................... 88
Generating pseudo-random numbers ...................................................................................... 94
Properly initializing a pseudo-random number generator .......................................................... 102
Creating cooked user-defined literals .................................................................................... 103
Creating raw user-defined literals ......................................................................................... 109
Using raw string literals to avoid escaping characters ............................................................ 114
Creating a library of string helpers ........................................................................................ 116
Parsing the content of a string using regular expressions ....................................................... 131
Replacing the content of a string using regular expressions ................................................... 136
Using std::string_view instead of constant string references ................................................... 139
Formatting and printing text with std::format and std::print .................................................. 142
Using std::format with user-defined types ............................................................................. 149
Chapter 3: Exploring Functions 155
Defaulted and deleted functions ........................................................................................... 155
Using lambdas with standard algorithms ............................................................................... 160
Using generic and template lambdas ..................................................................................... 166
Writing a recursive lambda ................................................................................................... 171
Writing function templates ................................................................................................... 176
Writing a function template with a variable number of arguments ......................................... 181
Using fold expressions to simplify variadic function templates ............................................... 186
Implementing the higher-order functions map and fold ......................................................... 190
Composing functions into a higher-order function ................................................................ 198
Uniformly invoking anything callable ................................................................................... 201
Chapter 4: Preprocessing and Compilation 207
Conditionally compiling your source code ............................................................................. 207
Using the indirection pattern for preprocessor stringification and concatenation ................... 214
Performing compile-time assertion checks with static_assert ................................................ 217
Conditionally compiling classes and functions with enable_if ................................................ 219
Selecting branches at compile time with constexpr if ............................................................. 225
Providing metadata to the compiler with attributes ............................................................... 228
Chapter 5: Standard Library Containers, Algorithms, and Iterators 235
Using vector as a default container ........................................................................................ 236
Using bitset for fixed-size sequences of bits ........................................................................... 241
Using vector<bool> for variable-size sequences of bits ........................................................... 248
Using the bit manipulation utilities ....................................................................................... 252
Finding elements in a range .................................................................................................. 255
Sorting a range ..................................................................................................................... 261
Initializing a range ............................................................................................................... 264
Using set operations on a range ............................................................................................. 268
Using iterators to insert new elements into a container .......................................................... 273
Writing your own random-access iterator .............................................................................. 276
Container access with non-member functions ....................................................................... 284
Selecting the right standard containers ................................................................................. 290
Chapter 6: General-Purpose Utilities 299
Expressing time intervals with chrono::duration ................................................................... 300
Working with calendars ........................................................................................................ 303
Converting times between time zones ................................................................................... 309
Measuring function execution time with a standard clock ...................................................... 312
Generating hash values for custom types ............................................................................... 316
Using std::any to store any value ........................................................................................... 319
Using std::optional to store optional values ........................................................................... 322
Chaining together computations that may or may not produce a value ................................... 327
Using std::variant as a type-safe union .................................................................................. 330
Visiting a std::variant ............................................................................................................ 333
Using std::expected to return a value or an error ................................................................... 339
Using std::span for contiguous sequences of objects .............................................................. 346
Using std::mdspan for multi-dimensional views of sequences of objects ................................. 349
Registering a function to be called when a program exits normally ........................................ 356
Using type traits to query properties of types ......................................................................... 359
Writing your own type traits ................................................................................................. 363
Using std::conditional to choose between types ..................................................................... 367
Providing logging details with source_location ...................................................................... 370
Using the stacktrace library to print the call sequence ........................................................... 372
Chapter 7: Working with Files and Streams 377
Reading and writing raw data from/to binary files ................................................................. 377
Reading and writing objects from/to binary files ................................................................... 387
Using streams on fixed-size external buffers .......................................................................... 392
Using localized settings for streams ...................................................................................... 395
Using I/O manipulators to control the output of a stream ....................................................... 401
Using monetary I/O manipulators ......................................................................................... 408
Using time I/O manipulators ................................................................................................. 411
Working with filesystem paths .............................................................................................. 414
Creating, copying, and deleting files and directories .............................................................. 418
Removing content from a file ................................................................................................ 423
Checking the properties of an existing file or directory .......................................................... 426
Enumerating the content of a directory ................................................................................. 431
Finding a file ........................................................................................................................ 436
Chapter 8: Leveraging Threading and Concurrency 441
Working with threads ........................................................................................................... 442
Synchronizing access to shared data with mutexes and locks ................................................. 447
Finding alternatives for recursive mutexes ............................................................................ 453
Handling exceptions from thread functions .......................................................................... 455
Sending notifications between threads .................................................................................. 458
Using promises and futures to return values from threads ..................................................... 465
Executing functions asynchronously ..................................................................................... 468
Using atomic types ............................................................................................................... 472
Implementing parallel map and fold with threads ................................................................. 481
Implementing parallel map and fold with tasks ..................................................................... 489
Implementing parallel map and fold with standard parallel algorithms .................................. 499
Using joinable threads and cancellation mechanisms ............................................................ 505
Synchronizing threads with latches, barriers, and semaphores ............................................. 510
Synchronizing writing to output streams from multiple threads ............................................. 517
Chapter 9: Robustness and Performance 523
Using exceptions for error handling ...................................................................................... 524
Using noexcept for functions that do not throw exceptions .................................................... 531
Ensuring constant correctness for a program ........................................................................ 535
Creating compile-time constant expressions ......................................................................... 541
Creating immediate functions ............................................................................................... 547
Optimizing code in constant-evaluated contexts .................................................................... 550
Using virtual function calls in constant expressions ............................................................... 555
Performing correct type casts ............................................................................................... 557
Implementing move semantics ............................................................................................. 562
Using unique_ptr to uniquely own a memory resource ........................................................... 568
Using shared_ptr to share a memory resource ....................................................................... 574
Consistent comparison with the operator <=> ........................................................................ 580
Comparing signed and unsigned integers safely .................................................................... 587
Chapter 10: Implementing Patterns and Idioms 593
Avoiding repetitive if-else statements in factory patterns ....................................................... 593
Implementing the pimpl idiom ............................................................................................. 597
Implementing the named parameter idiom ........................................................................... 604
Separating interfaces and implementations with the non-virtual interface idiom ....................... 608
Handling friendship with the attorney-client idiom ............................................................... 613
Static polymorphism with the curiously recurring template pattern ....................................... 617
Adding functionality to classes with mixins ........................................................................... 621
Handling unrelated types generically with the type erasure idiom ......................................... 625
Implementing a thread-safe singleton ................................................................................... 634
Chapter 11: Exploring Testing Frameworks 639
Getting started with Boost.Test .............................................................................................. 640
Writing and invoking tests with Boost.Test ............................................................................. 644
Asserting with Boost.Test ...................................................................................................... 650
Using fixtures in Boost.Test ................................................................................................... 653
Controlling output with Boost.Test ........................................................................................ 658
Getting started with Google Test ............................................................................................ 662
Writing and invoking tests with Google Test ........................................................................... 665
Asserting with Google Test .................................................................................................... 668
Using test fixtures with Google Test ....................................................................................... 671
Controlling output with Google Test ...................................................................................... 674
Getting started with Catch2 ................................................................................................... 677
Writing and invoking tests with Catch2 .................................................................................. 682
Asserting with Catch2 ........................................................................................................... 686
Controlling output with Catch2 ............................................................................................. 693
Chapter 12: C++ 20 Core Features 699
Working with modules .......................................................................................................... 700
Understanding module partitions ......................................................................................... 707
Specifying requirements on template arguments with concepts ............................................. 713
Using requires expressions and clauses ................................................................................. 719
Exploring abbreviated function templates ............................................................................. 723
xii Table of Contents
Iterating over collections with the ranges library ................................................................... 727
Exploring the standard range adaptors .................................................................................. 733
Converting a range to a container ......................................................................................... 743
Creating your own range view ............................................................................................... 745
Using constrained algorithms ............................................................................................... 751
Creating a coroutine task type for asynchronous computations .............................................. 757
Creating a coroutine generator type for sequences of values .................................................. 767
Generating a sequence of values with the std::generator type ................................................. 775
Other Books You May Enjoy 781
Index 785

 The updated third edition of Modern C++ Programming Cookbook addresses the latest features of C++23, such as the stack library, the expected and mdspan types, span buffers, formatting library improvements, and updates to the ranges library. It also gets into more C++20 topics not previously covered, such as sync output 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++.

What you will learn

  • Explore the new C++23 language and library features

  • Go deep into the most useful C++20 features

  • Learn to handle threading and concurrency for better performance

  • Solve complex string manipulation tasks efficiently with regex

  • Leverage the standard library for faster development

  • Master the file system library to work with files and directories

  • Work with different types of strings and understand compilation

  • See how you can use CRTP, mixins and other patterns in C++

Who this book is for

 This book is designed for entry- and intermediate-level programmers who already have a foundational understanding of the C++ programming language, but who are looking to master the language, implement the newest features, and become proficient modern C++ developers. Experienced C++ programmers can leverage the recipes in this book to quickly get up to speed on all the most important language and library features of C++11/14/17/20 and 23.


Похожее:

Список отзывов:

Нет отзывов к книге.