Book Image

C++ Fundamentals

By : Antonio Mallia, Francesco Zoffoli
Book Image

C++ Fundamentals

By: Antonio Mallia, Francesco Zoffoli

Overview of this book

C++ Fundamentals begins by introducing you to the C++ compilation model and syntax. You will then study data types, variable declaration, scope, and control flow statements. With the help of this book, you'll be able to compile fully working C++ code and understand how variables, references, and pointers can be used to manipulate the state of the program. Next, you will explore functions and classes — the features that C++ offers to organize a program — and use them to solve more complex problems. You will also understand common pitfalls and modern best practices, especially the ones that diverge from the C++98 guidelines. As you advance through the chapters, you'll study the advantages of generic programming and write your own templates to make generic algorithms that work with any type. This C++ book will guide you in fully exploiting standard containers and algorithms, understanding how to pick the appropriate one for each problem. By the end of this book, you will not only be able to write efficient code but also be equipped to improve the readability, performance, and maintainability of your programs.
Table of Contents (9 chapters)
C++ Fundamentals

Variadic Templates

We just saw how we can write a template that accepts parameters independently from their ref-ness.

But the two functions we talked about from the standard library, std::invoke and std::async, have an additional property: they can accept any number of arguments.

In a similar way, std::tuple, a type similar to a std::array but that can contain values of different types, can contain an arbitrary number of types.

How is it possible for a template to accept an arbitrary number of arguments of different types?

In the past, a solution to this problem was to provide a great number of overloads for the same function, or multiple implementations of the class or struct, one for each number of the parameters.

This is clearly code that is not easy to maintain, as it forces us to write the same code multiple times. Another drawback is that there is a limit to the number of template parameters, so if your code requires more parameters than what is provided, you do not have a way to use the...