Advanced C++ Programming Cookbook
eBook - ePub

Advanced C++ Programming Cookbook

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

Dr. Rian Quinn

Partager le livre
  1. 454 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Advanced C++ Programming Cookbook

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

Dr. Rian Quinn

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

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.

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Advanced C++ Programming Cookbook est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Advanced C++ Programming Cookbook par Dr. Rian Quinn en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Computer Science et Programming in C++. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2020
ISBN
9781838551841
Édition
1

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 des matiĂšres