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

Compartir libro
  1. 454 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Advanced C++ Programming Cookbook

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

Dr. Rian Quinn

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

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.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Advanced C++ Programming Cookbook un PDF/ePUB en línea?
Sí, puedes acceder a Advanced C++ Programming Cookbook de Dr. Rian Quinn en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming in C++. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2020
ISBN
9781838551841
Edición
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...

Índice