Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Template Metaprogramming with C++
Template Metaprogramming with C++

Template Metaprogramming with C++: Learn everything about C++ templates and unlock the power of template metaprogramming

eBook
$37.99
Paperback
$46.99
Subscription
Free Trial
Renews at $12.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Template Metaprogramming with C++

Chapter 1: An Introduction to Templates

As a C++ developer, you should be at least familiar if not well versed in template metaprogramming, in general, referred to in short as templates. Template metaprogramming is a programming technique that uses templates as blueprints for the compiler to generate code and help developers avoid writing repetitive code. Although general-purpose libraries use templates heavily, the syntax and the inner workings of templates in the C++ language can be discouraging. Even C++ Core Guidelines, which is a collection of dos and don'ts edited by Bjarne Stroustrup, the creator of the C++ language, and Herb Sutter, the chair of the C++ standardization committee, calls templates pretty horrendous.

This book is intended to shed light on this area of the C++ language and help you become prolific in template metaprogramming.

In this chapter, we will go through the following topics:

  • Understanding the need for templates
  • Writing your first...

Understanding the need for templates

Each language feature is designed to help with a problem or task that developers face when using that language. The purpose of templates is to help us avoid writing repetitive code that only differs slightly.

To exemplify this, let's take the classical example of a max function. Such a function takes two numerical arguments and returns the largest of the two. We can easily implement this as follows:

int max(int const a, int const b)
			{
			   return a > b ? a : b;
			}

This works pretty well, but as you can see, it will only work for values of the type int (or those that are convertible to int). What if we need the same function but with arguments of the type double? Then, we can overload this function (create a function with the same name but a different number or type of arguments) for the double type:

double max(double const a, double const b)
			{
			   return a > b ? a : b;
			}

However...

Writing your first templates

It is now time to see how templates are written in the C++ language. In this section, we will start with three simple examples, one for each of the snippets presented earlier.

A template version of the max function discussed previously would look as follows:

template <typename T>
			T max(T const a, T const b)
			{
			   return a > b ? a : b;
			}

You will notice here that the type name (such as int or double) has been replaced with T (which stands for type). T is called a type template parameter and is introduced with the syntax template<typename T> or typename<class T>. Keep in mind that T is a parameter, therefore it can have any name. We will learn more about template parameters in the next chapter.

At this point, this template that you put in the source code is only a blueprint. The compiler will generate code from it based on its use. More precisely, it will instantiate a function overload for each type...

Understanding template terminology

So far in this chapter, we have used the general term templates. However, there are four different terms describing the kind of templates we have written:

  • Function template is the term used for a templated function. An example is the max template seen previously.
  • Class template is the term used for a templated class (which can be defined either with the class, struct, or union keyword). An example is the vector class we wrote in the previous section.
  • Variable template is the term used for templated variables, such as the NewLine template from the previous section.
  • Alias template is the term used for templated type aliases. We will see examples for alias templates in the next chapter.

Templates are parameterized with one or more parameters (in the examples we have seen so far, there was a single parameter). These are called template parameters and can be of three categories:

  • Type template parameters, such as in template...

A brief history of templates

Template metaprogramming is the C++ implementation of generic programming. This paradigm was first explored in the 1970s and the first major languages to support it were Ada and Eiffel in the first half of the 1980s. David Musser and Alexander Stepanov defined generic programming, in a paper called Generic Programming, in 1989, as follows:

Generic programming centers around the idea of abstracting from concrete, efficient algorithms to obtain generic algorithms that can be combined with different data representations to produce a wide variety of useful software.

This defines a paradigm of programming where algorithms are defined in terms of types that are specified later and instantiated based on their use.

Templates were not part of the initial C with Classes language developed by Bjarne Stroustrup. Stroustrup's first papers describing templates in C++ appeared in 1986, one year after the publication of his book, The C++ Programming Language...

The pros and cons of templates

Before you start using templates, it's important to understand the benefits of using them as well as the disadvantages they may incur.

Let's start by pointing out the advantages:

  • Templates help us avoid writing repetitive code.
  • Templates foster the creation of generic libraries providing algorithms and types, such as the standard C++ library (sometimes incorrectly referred to as the STL), which can be used in many applications, regardless of their type.
  • The use of templates can result in less and better code. For instance, using algorithms from the standard library can help write less code that is likely easier to understand and maintain and also probably more robust because of the effort put into the development and testing of these algorithms.

When it comes to disadvantages, the following are worth mentioning:

  • The syntax is considered complex and cumbersome, although with a little practice this should not...

Summary

This chapter introduced the concept of templates in the C++ programming language.

We started by learning about the problems for which the solution is the use of templates. We then saw how templates look with simple examples of function templates, class templates, and variable templates. We introduced the basic terminology for templates, which we will discuss more in the forthcoming chapters. Toward the end of the chapter, we saw a brief history of templates in the C++ programming language. We ended the chapter with a discussion on the advantages and disadvantages of using templates. All these topics will lead us to understand the next chapters better.

In the next chapter, we will explore the fundamentals of templates in C++.

Questions

  1. Why do we need templates? What advantages do they provide?
  2. How do you call a function that is a template? What about a class that is a template?
  3. How many kinds of template parameters exist and what are they?
  4. What is partial specialization? What about full specialization?
  5. What are the main disadvantages of using templates?

Further reading

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Grasp the fundamentals of and learn to write effective C++ templates
  • Get up to speed with the latest C++20 template features such as constraints and concepts
  • Explore different patterns and idioms to integrate templates in your program design

Description

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.

Who is this book 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 the various idioms and patterns. Basic C++ coding experience is necessary to get started with this book.

What you will learn

  • Understand the syntax for all types of templates
  • Discover how specialization and instantiation works
  • Get to grips with template argument deduction and forwarding references
  • Write variadic templates with ease
  • Become familiar with type traits and conditional compilation
  • Restrict template arguments in C++20 with constraints and concepts
  • Implement patterns such as CRTP, mixins, and tag dispatching
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 19, 2022
Length: 480 pages
Edition : 1st
Language : English
ISBN-13 : 9781803243450
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Aug 19, 2022
Length: 480 pages
Edition : 1st
Language : English
ISBN-13 : 9781803243450
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$12.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$129.99 billed annually
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$179.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 140.97
Modern CMake for C++
$46.99
Template Metaprogramming with C++
$46.99
C++20 STL Cookbook
$46.99
Total $ 140.97 Stars icon
Banner background image

Table of Contents

15 Chapters
Part 1: Core Template Concepts Chevron down icon Chevron up icon
Chapter 1: An Introduction to Templates Chevron down icon Chevron up icon
Chapter 2: Template Fundamentals Chevron down icon Chevron up icon
Chapter 3: Variadic Templates Chevron down icon Chevron up icon
Part 2: Advanced Template Features Chevron down icon Chevron up icon
Chapter 4: Advanced Template Concepts Chevron down icon Chevron up icon
Chapter 5: Type Traits and Conditional Compilation Chevron down icon Chevron up icon
Chapter 6: Concepts and Constraints Chevron down icon Chevron up icon
Part 3: Applied Templates Chevron down icon Chevron up icon
Chapter 7: Patterns and Idioms Chevron down icon Chevron up icon
Chapter 8: Ranges and Algorithms Chevron down icon Chevron up icon
Chapter 9: The Ranges Library Chevron down icon Chevron up icon
Closing Notes Chevron down icon Chevron up icon
Assignment Answers Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(14 Ratings)
5 star 78.6%
4 star 7.1%
3 star 14.3%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Christian Albaret Feb 16, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This the first book I am reading of the 5 I bought at once. I have been developping a lot in C++, much on and with templates, and some metaprogramming. The book goes through the features, tricks, and pitfalls of C++ templates, with many explanations., and then demonstrates some programming patterns. Much can readily be found in reference documentation, but they are hard to read, and one easky gets lost. The discussions in the book are what makes the difference.
Feefo Verified review Feefo
Krishnan Raghavan Nov 30, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have always wanted to understand how templates are written in C++ for a very long time and was very excited when I saw this book. Confession: I am yet to read the whole book but I thought I would write a small review of the few initial chapters that I have read in case it helps anyone.Metaprogramming is the programming technique of using templates to generate code at compile-time that is then merged with the rest of the source code for compiling a final program. This book is divided into 3 parts. The first two parts will give the user a good understanding of all the different kinds of templates available in C++. The third part will help the reader put their knowledge into practice to perform metaprogramming with templates.The author has ensured that this book caters to all levels of C++ programmers (Beginners, Intermediate and Advanced). At the end of each chapter, there are questions that will ensure that the concepts learned in the chapter are tested. Please do not skip these. Further reading will give the reader about what to read next to ensure that the chapter lessons as well understood.I will post a detailed chapter-wise review in the next few days.A big shout out to Marius Bancila for writing a book a such a difficult topic.
Amazon Verified review Amazon
Adam Rackis Jan 02, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I’ve read a lot of C++ books, but this was one of my favorites. It’s a solid deep dive into C++ templates. It starts slowly enough for non-experts to keep up, and then covers some solid material, including new C++20 content.Highly recommend.
Amazon Verified review Amazon
POE Dec 29, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is refreshing in its approach -- it covers one topic in great depth. Template metaprogramming is a development technique that we use to create transactional or temporary source code which is merged with the rest of our source code. The book does a great job of explaining the what as well as the why and how.The book only requires a basic understand of C++, so it is relevant for novice, intermediary, and advanced C++ programmers. If you are a C++ developer, I recommend reading this book. You should, at least, find it interesting if not actionable in your work.
Amazon Verified review Amazon
Vine Reviewer Nov 15, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Since I've taught C++ courses, and have used templates extensively, I figured this book would be an easy read.Well parts of it were a fairly easy read -- but the author dived a little deeper than I expected into some of the details. For instance, I knew about type traits, but I didn't know how they were implemented. The author showed the background theory, and did a good job of explaining how/why they are used.I learned quite a bit about C++20 features, too. The author did an in-depth coverage of constraints and concepts, new features I had heard about, but never used. The main take-away I got from those topics was that those new features yielded *much* clearer error messages. If you have ever struggled with VS2017 compiler error messages, you will *love* constraints and concepts.The patterns & idioms section was a slow read, because it had a lot of new (to me) information.The last parts on ranges and algorithms, was a bit easier reading, since I've made extensive use of most of the material there.I was very impressed with Marius Bancila's writing style, although there were a few word choices that hinted that English was not his native language. But his English is excellent, as is his ability to teach fairly complex topics well. About the only thing I would have suggested (if I had been an editor) is the simple way to approach templates as a novice. Namely, write and test your class (or function) as a non-template, using a specific type, then convert it to a templated version. The reverse is also true; because template syntax is ugly (IMNSHO), the easiest way to understand a template written by somebody else is to copy it, and substitute some simple type for the template parameter(s) to get rid of the ugly template syntax.But that's not enough of a shortcoming to knock any points off. In fact, I think this book is more than just "good" -- it will be an important part of my reference library.Disclaimer: I was provided a copy of this book by Packt for review. This review is my honest opinion of the book.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela