Advanced C++ Programming Cookbook
eBook - ePub

Advanced C++ Programming Cookbook

Become an expert C++ programmer by mastering concepts like templates, concurrency, and type deduction

  1. 454 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Advanced C++ Programming Cookbook

Become an expert C++ programmer by mastering concepts like templates, concurrency, and type deduction

About this book

A recipe-based guide to refining your C++ programming skills with the help of coding best practices, advanced programming concepts, and the latest features of C++17 and C++20

Key Features

  • Learn how to develop and design your own libraries
  • Find solutions to your app development problems and implement them in a highly reusable manner, following library development best practices
  • Explore advanced C++ features such as containers, coroutines, and modules

Book Description

If you think you've mastered C++ and know everything it takes to write robust applications, you'll be in for a surprise. With this book, you'll gain comprehensive insights into C++, covering exclusive tips and interesting techniques to enhance your app development process.

You'll kick off with the basic principles of library design and development, which will help you understand how to write reusable and maintainable code. You'll then discover the importance of exception safety, and how you can avoid unexpected errors or bugs in your code. The book will take you through the modern elements of C++, such as move semantics, type deductions, and coroutines. As you advance, you'll delve into template programming - the standard tool for most library developers looking to achieve high code reusability. You'll explore the STL and learn how to avoid common pitfalls while implementing templates. Later, you'll learn about the problems of multithreaded programming such as data races, deadlocks, and thread starvation. You'll also learn high-performance programming by using benchmarking tools and libraries. Finally, you'll discover advanced techniques for debugging and testing to ensure code reliability.

By the end of this book, you'll have become an expert at C++ programming and will have gained the skills to solve complex development problems with ease.

What you will learn

  • Solve common C++ development problems by implementing solutions in a more generic and reusable way
  • Achieve different levels of exception safety guarantees by introducing precise declarations
  • Write library-quality code that meets professional standards
  • Practice writing reliable, performant code that exposes consistent behavior in programs
  • Understand why you need to implement design patterns and how it's done
  • Work with complex examples to understand various aspects of good library design

Who this book is for

This book is for intermediate and expert-level C++ developers who are looking to explore the lesser known functionalities of the language to improve the efficiency of their code and the way they develop applications. Basic knowledge of object-oriented programming concepts and the Standard Template Library (STL) is assumed.

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription.
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Yes! You can use the Perlego app on both iOS or Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app.
Yes, you can access Advanced C++ Programming Cookbook by Dr. Rian Quinn in PDF and/or ePUB format, as well as other popular books in Computer Science & Object Oriented Programming. We have over one million books available in our catalogue for you to explore.

Using Templates for Generic Programming

In this chapter, we will learn advanced template programming techniques. These techniques include the ability to change the implementation of a template class based on the type that is provided, how to work different types of arguments including how to properly forward them, how to optimize your code both at runtime and compile time, and how to use some new features added to C++17. This is important because it provides a better understanding of how template programming works as well as how to ensure your templates are performing the way you expect.
Too often, we write template code assuming it is executing one way when, in fact, it is executing in another, either generating unreliable code, code with unexpected performance penalties, or both. This chapter will explain how to avoid these issues and provide the foundation for writing proper generic programs.
The recipes in this chapter are as follows:
  • Implementing SFINAE
  • Learning perfect forwarding
  • Using if constexpr
  • Using tuples to work with parameter packs
  • Using traits to vary the behavior of template implementations
  • Learning how to implement template<auto>
  • Working with explicit template declarations

Technical requirements

To compile and run the examples in this chapter, you must have administrative access to a computer running Ubuntu 18.04 with a functional internet connection. Prior to running these examples, install the following:
> sudo apt-get install build-essential git cmake
If this is installed on any operating system other than Ubuntu 18.04, then GCC 7.4 or higher and CMake 3.6 or higher will be required.

Implementing SFINAE

In this recipe, we will learn how to use Substitution Failure Is Not An Error (SFINAE). This recipe is important because, often, we create templates without ensuring the types passed to a template are what we expect. This can lead to unexpected behavior, suboptimal performance, and even buggy, unreliable code.
SFINAE allows us to be explicit about what types we are expecting in our template. It also provides us with a means to change the behavior of our templates based on the types we are provided. The problem with SFINAE for some is that this concept is difficult to understand. Our goal in this recipe is to demystify SFINAE and show how you can use this in your own code.

Getting ready

Before beginning, please ensure that all of the technical requirements are met, including installing Ubuntu 18.04 or higher and running the following in a Terminal window:
> sudo apt-get install build-essential git cmake
This will ensure your operating system has the proper tools to compile and execute the examples in this recipe. Once this is complete, open a new Terminal. We will use this Terminal to download, compile, and run our examples.

How to do it...

You need to perform the following steps to try this recipe:
  1. From a new Terminal, run the following to download the source code:
> cd ~/
> git clone https://github.com/PacktPublishing/Advanced-CPP-CookBook.git
> cd Advanced-CPP-CookBook/chapter04
  1. To compile the source code, run the following:
> cmake .
> make recipe01_examples
  1. Once the source code is compiled, you can execute each example in this recipe by running the following commands:
> ./recipe01_example01
The answer is: 23
The answer is: 42

> ./recipe01_example02
The answer is: 42

> ./recipe01_example03
The answer is: 42

> ./recipe01_example04
The answer is: 42

> ./recipe01_example05
The answer is: 42
The answer is: 42
The answer is: 42.12345678
In the next section, we will step through each of these examples and explain what each example program does and how it relates to the lessons being taught in this recipe.

How it works...

In this recipe, you will learn how to incorporate SFINAE in your own code. To start, we must first understand what SFINAE is and how the standard library uses it to implement type traits. Without knowing how type traits are implemented, it can be difficult to understand how to use them.
To start, the most important thing to understand with SFINAE is what its name says, which is that a substitution failure is not an error. What this means is that when a template type is being substituted, if a failure occurs, the compiler will not generate an error as a result. For example, we can write the following:
#include <iostream>

struct the_answer
{
using type = unsigned;
};

template<typename T>
void foo(typename T::type t)
{
std::cout << "The answer is not: " << t << '\n';
}

template<typename T>
void foo(T t)
{
std::cout << "The answer is: " << t << '\n';
}

int main(void)
{
foo<the_answer>(23);
foo<int>(42);

return 0;
}
The output for each of these are depicted here:
The answer is: 23
The answer is: 42
In this example, we have created two versions of the foo() function. This first version takes a T type that has a type alias that we use to create the function's parameter. The second version just takes the T type itself. We then use both versions of the foo() function, one with an integer and the other with a struct that defines the type alias.
The takeaway from the preceding example is that when we call the foo<int>() version of the foo() function, the compiler doesn't generate an error when it attempts to match the int type with the version of the foo() function that takes a type with the type alias. This is what SFINAE is. All it says is that when the compil...

Table of contents

  1. Title Page
  2. Copyright and Credits
  3. Dedication
  4. About Packt
  5. Contributors
  6. Preface
  7. Getting Started with Library Development
  8. Using Exceptions for Error Handling
  9. Implementing Move Semantics
  10. Using Templates for Generic Programming
  11. Concurrency and Synchronization
  12. Optimizing Your Code for Performance
  13. Debugging and Testing
  14. Creating and Implementing Your Own Container
  15. Exploring Type Erasure
  16. An In-Depth Look at Dynamic Allocation
  17. Common Patterns in C++
  18. A Closer Look at Type Deduction
  19. Bonus - Using C++20 Features
  20. Other Books You May Enjoy