Template Metaprogramming with C++ - Marius Bancila - E-Book

Template Metaprogramming with C++ E-Book

Marius Bancila

0,0
33,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Learn how the metaprogramming technique enables you to create data structures and functions that allow computation to happen at compile time. With this book, you'll realize how templates help you avoid writing duplicate code and are key to creating generic libraries, such as the standard library or Boost, that can be used in a multitude of programs.
The introductory chapters of this book will give you insights into the fundamentals of templates and metaprogramming. You'll then move on to practice writing complex templates and exploring advanced concepts such as template recursion, template argument deduction, forwarding references, type traits, and conditional compilation. Along the way, you'll learn how to write variadic templates and how to provide requirements to the template arguments with C++20 constraints and concepts. Finally, you'll apply your knowledge of C++ metaprogramming templates to implement various metaprogramming patterns and techniques.
By the end of this book, you'll have learned how to write effective templates and implement metaprogramming in your everyday programming journey.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 434

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Template Metaprogramming with C++

Learn everything about C++ templates and unlock the power of template metaprogramming

Marius Bancila

BIRMINGHAM—MUMBAI

Template Metaprogramming with C++

Copyright © 2022 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, 
or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express 
or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Associate Group Product Manager: Gebin George

Content Development Editor: Rosal Colaco

Technical Editor: Pradeep Sahu

Copy Editor: Safis Editing

Project Coordinator: Manisha Singh

Proofreader: Safis Editing

Indexer: Sejal Dsilva

Production Designer: Vijay Kamble

Business Development Executive: Kriti Sharma

Marketing Coordinator: Sonakshi Bubbar

First published: July 2022

Production reference: 1220722

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80324-345-0

www.packt.com

To the curious minds that always want to learn more.

– Marius Bancila

Contributors

About the author

Marius Bancila is a software engineer with two decades of experience in developing solutions for line of business applications and more. He is the author of Modern C++ Programming Cookbook and The Modern C++ Challenge. He works as a software architect and is focused on Microsoft technologies, mainly developing desktop applications with C++ and C#. He is passionate about sharing his technical expertise with others and, for that reason, he has been recognized as a Microsoft MVP for C++ and later developer technologies since 2006. Marius lives in Romania and is active in various online communities.

About the reviewer

Aleksei Goriachikh has 8+ experience in C++ programming. After graduating from Novosibirsk State University in 2012 with a master’s degree in mathematics, Aleksei has worked on research projects in the areas of computational mathematics and optimization, a geometric kernel for CAD systems, and a multi-threaded library for autonomous driving. Aleksei’s last professional interest is pre-silicon modelling.

Table of Contents

Preface

Part 1: Core Template Concepts

Chapter 1: An Introduction to Templates

Understanding the need for templates

Writing your first templates

Understanding template terminology

A brief history of templates

The pros and cons of templates

Summary

Questions

Further reading

Chapter 2: Template Fundamentals

Defining function templates

Defining class templates

Defining member function templates

Understanding template parameters

Type template parameters

Non-type template parameters

Template template parameters

Default template arguments

Understanding template instantiation

Implicit instantiation

Explicit instantiation

Understanding template specialization

Explicit specialization

Partial specialization

Defining variable templates

Defining alias templates

Exploring generic lambdas and lambda templates

Summary

Questions

Further reading

Chapter 3: Variadic Templates

Understanding the need for variadic templates

Variadic function templates

Parameter packs

Understanding parameter packs expansion

Variadic class templates

Fold expressions

Variadic alias templates

Variadic variable templates

Summary

Questions

Further reading

Part 2: Advanced Template Features

Chapter 4: Advanced Template Concepts

Understanding name binding and dependent names

Two-phase name lookup

Dependent type names

Dependent template names

Current instantiation

Exploring template recursion

Function template argument deduction

Class template argument deduction

Forwarding references

The decltype specifier

The std::declval type operator

Understanding friendship in templates

Summary

Questions

Further readings

Chapter 5: Type Traits and Conditional Compilation

Understanding and defining type traits

Exploring SFINAE and its purpose

Enabling SFINAE with the enable_if type trait

Using constexpr if

Exploring the standard type traits

Querying the type category

Querying type properties

Querying supported operations

Querying type relationships

Modifying cv-specifiers, references, pointers, or a sign

Miscellaneous transformations

Seeing real-world examples of using type traits

Implementing a copy algorithm

Building a homogenous variadic function template

Summary

Questions

Further reading

Chapter 6: Concepts and Constraints

Understanding the need for concepts

Defining concepts

Exploring requires expressions

Simple requirements

Type requirements

Compound requirements

Nested requirements

Composing constraints

Learning about the ordering of templates with constraints

Constraining non-template member functions

Constraining class templates

Constraining variable templates and template aliases

Learning more ways to specify constraints

Using concepts to constrain auto parameters

Exploring the standard concepts library

Summary

Questions

Further reading

Part 3: Applied Templates

Chapter 7: Patterns and Idioms

Dynamic versus static polymorphism

The Curiously Recurring Template Pattern

Limiting the object count with CRTP

Adding functionality with CRTP

Implementing the composite design pattern

The CRTP in the standard library

Mixins

Type erasure

Tag dispatching

Alternatives to tag dispatching

Expression templates

Using ranges as an alternative to expression templates

Typelists

Using typelists

Implementing operations on typelists

Summary

Questions

Further reading

Chapter 8: Ranges and Algorithms

Understanding the design of containers, iterators, and algorithms

Creating a custom container and iterator

Implementing a circular buffer container

Implementing an iterator type for the circular buffer container

Writing a custom general-purpose algorithm

Summary

Questions

Chapter 9: The Ranges Library

Advancing from abstract ranges to the ranges library

Understanding range concepts and views

Exploring more examples

Understanding the constrained algorithms

Writing your own range adaptor

Summary

Questions

Further reading

Appendix: Closing Notes

Assignment Answers

Chapter 1, Introduction to Templates

Chapter 2, Template Fundamentals

Chapter 3, Variadic Templates

Chapter 4, Advanced Template Concepts

Chapter 5, Type Traits and Conditional Compilation

Chapter 6, Concepts and Constraints

Chapter 7, Patterns and Idioms

Chapter 8, Ranges and Algorithms

Chapter 9, The Ranges Library

Other Books You May Enjoy

Preface

The C++ programming language is one of the most widely used in the world and it has been so for decades. Its success isn’t due just to the performance it provides or maybe to its ease of use, which many would argue against, but probably to its versatility. C++ is a general-purpose, multi-paradigm programming language that blends together procedural, functional, and generic programming.

Generic programming is a paradigm of writing code such as that entities such as functions and classes are written in terms of types that are specified later. These generic entities are instantiated only when needed for specific types that are specified as arguments. These generic entities are known as templates in C++.

Metaprogramming is the programming technique of using templates (and constexpr functions in C++) to generate code at compile-time that is then merged with the rest of the source code for compiling a final program. Metaprogramming implies that at least an input or an output is a type.

Templates in C++ have a reputation of being pretty horrendous, as described in the C++ Core Guideless (a document of dos and don’ts maintained by Bjarne Stroustrup and Herb Sutter). However, they make generic libraries possible such as the C++ Standard Library that C++ developers use all the time. Whether you’re writing templates yourself or just using templates written by others (such as standard containers or algorithms), templates are most likely part of your daily code.

This book is intended to provide a good understanding of all the spectrum of templates available in C++ (from their basic syntax to concepts in C++20). This will be the focus of the first two parts of the book. The third and final part will help you put the newly acquired knowledge into practice to perform metaprogramming with templates.

Who this book is for?

This book is for beginner-to-intermediate C++ developers who want to learn about template metaprogramming as well as advanced C++ developers looking to get up to speed with the new C++20 features related to templates and the various idioms and patterns. Basic C++ coding experience is necessary to get started with this book.

What this book covers

Chapter 1, Introduction to Templates, provides an introduction to the concept of template metaprogramming in C++, with several simple examples, and a discussion on why we need templates and what are the pros and cons of using templates.

Chapter 2, Template Fundamentals, explores all forms of templates in C++: function templates, class templates, variable templates, and alias templates. For each of these, we discuss the syntax and the details of how they work. Furthermore, the key concepts of template instantiation and specialization are addressed here.

Chapter 3, Variadic Templates, is dedicated entirely to variadic templates which are templates that have a variable number of template parameters. We discuss in detail variadic function templates, variadic class templates, variadic alias templates, and variadic variable templates, parameter packs and how they are expanded, as well as fold expressions that help us simplify the writing of variadic templates.

Chapter 4, Advanced Template Concepts, groups a series of advanced template concepts such as dependent names and name lookup, template argument deduction, template recursion, perfect forwarding, generic and template lambdas. By understanding these topics, readers will be able to greatly expand the variety of templates they can read or write.

Chapter 5, Type Traits and Conditional Compilation, is dedicated to type traits. The reader will learn about type traits, what traits the standard library provides, and how they can be used to solve different problems.

Chapter 6, Concepts and Constraints, presents the new C++20 mechanism for defining requirements for template arguments with concepts and constraints. You will learn about the various ways to specify constraints. Moreover, we provide an overview of the content of the C++20 standard concepts library.

Chapter 7, Patterns and Idioms, explores a series of unrelated advanced topics of using the knowledge learned so far into implementing various patterns. We explore the concepts of static polymorphism, type erasure, tag dispatching, and patterns such as the curiously recursive template pattern, expression templates, mixins, and typelists.

Chapter 8, Ranges and Algorithms, is dedicated to understanding containers, iterators, and algorithms, which are the core components of the standard template library. You will learn here how to write a generic container and an iterator type for it as well as a general-purpose algorithm.

Chapter 9, The Ranges Library, explores the new C++20 Ranges library with its key features such as ranges, range adaptors, and constrained algorithms. These enable us to write simpler code for working with ranges. Furthermore, you will also learn here how to write your own range adaptor.

Appendix is a short epilog that provides a summary of the book.

Assignment Answers contains all the answers to the questions from all the chapters.

To get the most out of this book

To get started with this book, you need to have some basic knowledge of the C++ programming language. You need to know the syntax and fundamentals about classes, functions, operators, function overloading, inheritance, virtual functions, and more. However, no knowledge of templates is required, as this book will teach you everything from scratch.

All the code samples in this book are cross-platform. That means you can use any compiler to build and run them. However, although many snippets work with a C++11 compiler, there are also snippets that require a C++17 or C++20 compliant compiler. Therefore, we recommend you use a compiler version that supports C++20 so you can run all the samples. The samples in this book have been tested with MSVC 19.30 (Visual Studio 2022), GCC 12.1/13, and Clang 13/14. If you don’t have such a C++20 compliant compiler on your machine, you can try one online. We recommend one of the following:

Compiler Explorer (https://godbolt.org/)Wandbox (https://wandbox.org/)C++ Insights (https://cppinsights.io/)

The C++ Insights online tools will be referred several times in the book for analyzing the code generated by the compiler.

You should refer to the page, https://en.cppreference.com/w/cpp/compiler_support, if you want to check compilers support for different versions of the C++ standard.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Mentions and further readings

Throughout the book, we are referring multiple times to the C++ standard. This document is copy-righted by the International Organization for Standardization. The official C++ standard document can be purchased from here: https://www.iso.org/standard/79358.html. However, multiple drafts of the C++ standard as well as the sources used to generate them are freely available on GitHub at https://github.com/cplusplus/draft. You cand find additional information about the C++ standard at https://isocpp.org/std/the-standard.

A great online resource for C++ developers is the C++ Reference website, available at https://en.cppreference.com/. This provides exhaustive documentation of the C++ language directly derived from the C++ standard. Content from the C++ Reference is quoted several times in the book. The C++ Reference content is licensed under CC-BY-SA license, https://en.cppreference.com/w/Cppreference:Copyright/CC-BY-SA.

At the end of each chapter, you will find a section called Further reading. This section contains a list of readings used as a bibliography and recommended for deepening your knowledge of the presented topics.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Template-Metaprogramming-with-CPP. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/Un8j5.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “This problem can be fixed by making init a dependent name.”

A block of code is set as follows:

template <typename T> struct parser : base_parser<T> { void parse() { this->init(); // OK std::cout << "parse\n"; } };

Any command-line input or output is written as follows:

fatal error: recursive template instantiation exceeded maximum

depth of 1024

use -ftemplate-depth=N to increase recursive template

instantiation depth

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “The capacity is 8, the size is 0, and the head and tail both point to index 0.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read Template Metaprogramming with C++, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Part 1: Core Template Concepts

In this part, you will begin with an introduction to templates and understand their benefits. You will then learn about the syntax for writing function templates, class templates, variable templates, and alias templates. You will explore concepts such as template instantiation and template specialization and learn how to write templates with a variable number of arguments.

This part comprises the following chapters:

Chapter 1, Introduction to TemplatesChapter 2, Template FundamentalsChapter 3, Variadic Templates