Home > Store

C++ Templates: The Complete Guide, 2nd Edition

eBook (Watermarked)

  • Your Price: $61.59
  • List Price: $76.99
  • Includes EPUB and PDF
  • About eBook Formats
  • This eBook includes the following formats, accessible from your Account page after purchase:

    ePub EPUB The open industry format known for its reflowable content and usability on supported mobile devices.

    Adobe Reader PDF The popular standard, used most often with the free Acrobat® Reader® software.

    This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.

Also available in other formats.

Register your product to gain access to bonus material or receive a coupon.

Description

  • Copyright 2018
  • Dimensions: 7-3/8" x 9-1/8"
  • Pages: 832
  • Edition: 2nd
  • eBook (Watermarked)
  • ISBN-10: 0-13-477879-0
  • ISBN-13: 978-0-13-477879-2

Templates are among the most powerful features of C++, but they remain misunderstood and underutilized, even as the C++ language and development community have advanced. In C++ Templates, Second Edition, three pioneering C++ experts show why, when, and how to use modern templates to build software that’s cleaner, faster, more efficient, and easier to maintain.

Now extensively updated for the C++11, C++14, and C++17 standards, this new edition presents state-of-the-art techniques for a wider spectrum of applications. The authors provide authoritative explanations of all new language features that either improve templates or interact with them, including variadic templates, generic lambdas, class template argument deduction, compile-time if, forwarding references, and user-defined literals. They also deeply delve into fundamental language concepts (like value categories) and fully cover all standard type traits.

The book starts with an insightful tutorial on basic concepts and relevant language features. The remainder of the book serves as a comprehensive reference, focusing first on language details and then on coding techniques, advanced applications, and sophisticated idioms. Throughout, examples clearly illustrate abstract concepts and demonstrate best practices for exploiting all that C++ templates can do.

  • Understand exactly how templates behave, and avoid common pitfalls
  • Use templates to write more efficient, flexible, and maintainable software
  • Master today’s most effective idioms and techniques
  • Reuse source code without compromising performance or safety
  • Benefit from utilities for generic programming in the C++ Standard Library
  • Preview the upcoming concepts feature

The companion website, tmplbook.com, contains sample code and additional updates.

Extras

Author's Site

For code examples, errata, feedback, and more, please visit the authors' site at http://www.tmplbook.com.

Sample Content

Sample Pages

Download the sample pages (includes Chapter 4 and the Index)

Table of Contents

Preface xxiii

Acknowledgments for the Second Edition xxv

Acknowledgments for the First Edition xxvii

About This Book xxix

Part I: The Basics 1

Chapter 1: Function Templates 3

1.1 A First Look at Function Templates 3

1.2 Template Argument Deduction 7

1.3 Multiple Template Parameters 9

1.4 Default Template Arguments 13

1.5 Overloading Function Templates 15

1.6 But, Shouldn’t We . . . ? 20

1.7 Summary 21

Chapter 2: Class Templates 23

2.1 Implementation of Class Template Stack 23

2.2 Use of Class Template Stack 27

2.3 Partial Usage of Class Templates 29

2.4 Friends 30

2.5 Specializations of Class Templates 31

2.6 Partial Specialization 33

2.7 Default Class Template Arguments 36

2.8 Type Aliases38

2.9 Class Template Argument Deduction 40

2.10 Templatized Aggregates 43

2.11 Summary 44

Chapter 3: Nontype Template Parameters 45

3.1 Nontype Class Template Parameters 45

3.2 Nontype Function Template Parameters 48

3.3 Restrictions for Nontype Template Parameters 49

3.4 Template Parameter Type auto 50

3.5 Summary 54

Chapter 4: Variadic Templates 55

4.1 Variadic Templates 55

4.2 Fold Expressions 58

4.3 Application of Variadic Templates 60

4.4 Variadic Class Templates and Variadic Expressions 61

4.5 Summary 66

Chapter 5: Tricky Basics 67

5.1 Keyword typename 67

5.2 Zero Initialization 68

5.3 Using this-> 70

5.4 Templates for Raw Arrays and String Literals 71

5.5 Member Templates 74

5.6 Variable Templates 80

5.7 Template Template Parameters 83

5.8 Summary 89

Chapter 6: Move Semantics and enable_if<> 91

6.1 Perfect Forwarding 91

6.2 Special Member Function Templates 95

6.3 Disable Templates with enable_if<> 98

6.4 Using enable_if<> 99

6.5 Using Concepts to Simplify enable_if<> Expressions 103

6.6 Summary 104

Chapter 7: By Value or by Reference? 105

7.1 Passing by Value 106

7.2 Passing by Reference 108

7.3 Using std::ref() and std::cref() 112

7.4 Dealing with String Literals and Raw Arrays 115

7.5 Dealing with Return Values 117

7.6 Recommended Template Parameter Declarations 118

7.7 Summary 121

Chapter 8: Compile-Time Programming 123

8.1 Template Metaprogramming 123

8.2 Computing with constexpr 125

8.3 Execution Path Selection with Partial Specialization 127

8.4 SFINAE (Substitution Failure Is Not An Error) 129

8.5 Compile-Time if 134

8.6 Summary 135

Chapter 9: Using Templates in Practice 137

9.1 The Inclusion Model 137

9.2 Templates and inline 140

9.3 Precompiled Headers 141

9.4 Decoding the Error Novel 143

9.5 Afternotes 149

9.6 Summary 150

Chapter 10: Basic Template Terminology 151

10.1 “Class Template” or “Template Class”? 151

10.2 Substitution, Instantiation, and Specialization 152

10.3 Declarations versus Definitions 153

10.4 The One-Definition Rule 154

10.5 Template Arguments versus Template Parameters 155

10.6 Summary 156

Chapter 11: Generic Libraries 157

11.1 Callables 157

11.2 Other Utilities to Implement Generic Libraries 164

11.3 Perfect Forwarding Temporaries 167

11.4 References as Template Parameters 167

11.5 Defer Evaluations 171

11.6 Things to Consider When Writing Generic Libraries 172

11.7 Summary 173

Part II: Templates in Depth 175

Chapter 12: Fundamentals in Depth 177

12.1 Parameterized Declarations 177

12.2 Template Parameters 185

12.3 Template Arguments 192

12.4 Variadic Templates 200

12.5 Friends 209

12.6 Afternotes 213

Chapter 13: Names in Templates 215

13.1 Name Taxonomy 215

13.2 Looking Up Names 217

13.3 Parsing Templates 224

13.4 Inheritance and Class Templates 236

13.5 Afternotes 240

Chapter 14: Instantiation 243

14.1 On-Demand Instantiation 243

14.2 Lazy Instantiation 245

14.3 The C++ Instantiation Model 249

14.4 Implementation Schemes 255

14.5 Explicit Instantiation 260

14.6 Compile-Time if Statements 263

14.7 In the Standard Library 265

14.8 Afternotes 266

Chapter 15: Template Argument Deduction 269

15.1 The Deduction Process 269

15.2 Deduced Contexts 271

15.3 Special Deduction Situations 273

15.4 Initializer Lists 274

15.5 Parameter Packs 275

15.6 Rvalue References 277

15.7 SFINAE (Substitution Failure Is Not An Error) 284

15.8 Limitations of Deduction 286

15.9 Explicit Function Template Arguments 291

15.10 Deduction from Initializers and Expressions 293

15.11 Alias Templates 312

15.12 Class Template Argument Deduction 313

15.13 Afternotes 321

Chapter 16: Specialization and Overloading 323

16.1 When “Generic Code” Doesn’t Quite Cut It 323

16.2 Overloading Function Templates 326

16.3 Explicit Specialization 338

16.4 Partial Class Template Specialization 347

16.5 Partial Variable Template Specialization 351

16.6 Afternotes 352

Chapter 17: Future Directions 353

17.1 Relaxed typename Rules 354

17.2 Generalized Nontype Template Parameters 354

17.3 Partial Specialization of Function Templates 356

17.4 Named Template Arguments 358

17.5 Overloaded Class Templates 359

17.6 Deduction for Nonfinal Pack Expansions 360

17.7 Regularization of void 361

17.8 Type Checking for Templates 361

17.9 Reflective Metaprogramming 363

17.10 Pack Facilities 365

17.11 Modules 366

Part III: Templates and Design 367

Chapter 18: The Polymorphic Power of Templates 369

18.1 Dynamic Polymorphism 369

18.2 Static Polymorphism 372

18.3 Dynamic versus Static Polymorphism 375

18.4 Using Concepts 377

18.5 New Forms of Design Patterns 379

18.6 Generic Programming 380

18.7 Afternotes 383

Chapter 19: Implementing Traits 385

19.1 An Example: Accumulating a Sequence 385

19.2 Traits versus Policies and Policy Classes 394

19.3 Type Functions 401

19.4 SFINAE-Based Traits 416

19.5 IsConvertibleT 428

19.6 Detecting Members 431

19.7 Other Traits Techniques 440

19.8 Type Classification 448

19.9 Policy Traits 458

19.10 In the Standard Library 461

19.11 Afternotes 462

Chapter 20: Overloading on Type Properties 465

20.1 Algorithm Specialization 465

20.2 Tag Dispatching 467

20.3 Enabling/Disabling Function Templates 469

20.4 Class Specialization 477

20.5 Instantiation-Safe Templates 482

20.6 In the Standard Library 487

20.7 Afternotes 488

Chapter 21: Templates and Inheritance 489

21.1 The Empty Base Class Optimization (EBCO) 489

21.2 The Curiously Recurring Template Pattern (CRTP) 495

21.3 Mixins 508

21.4 Named Template Arguments 512

21.5 Afternotes 515

Chapter 22: Bridging Static and Dynamic Polymorphism 517

22.1 Function Objects, Pointers, and std::function<> 517

22.2 Generalized Function Pointers 519

22.3 Bridge Interface 522

22.4 Type Erasure 523

22.5 Optional Bridging 525

22.6 Performance Considerations 527

22.7 Afternotes 528

Chapter 23: Metaprogramming 529

23.1 The State of Modern C++ Metaprogramming 529

23.2 The Dimensions of Reflective Metaprogramming 537

23.3 The Cost of Recursive Instantiation 539

23.4 Computational Completeness 542

23.5 Recursive Instantiation versus Recursive Template Arguments 542

23.6 Enumeration Values versus Static Constants 543

23.7 Afternotes 545

Chapter 24: Typelists 549

24.1 Anatomy of a Typelist 549

24.2 Typelist Algorithms 551

24.3 Nontype Typelists 566

24.4 Optimizing Algorithms with Pack Expansions 569

24.5 Cons-style Typelists 571

24.6 Afternotes 573

Chapter 25: Tuples 575

25.1 Basic Tuple Design 576

25.2 Basic Tuple Operations 579

25.3 Tuple Algorithms 581

25.4 Expanding Tuples 592

25.5 Optimizing Tuple 593

25.6 Tuple Subscript 599

25.7 Afternotes 601

Chapter 26: Discriminated Unions 603

26.1 Storage 604

26.2 Design 606

26.3 Value Query and Extraction 610

26.4 Element Initialization, Assignment and Destruction 611

26.5 Visitors 617

26.6 Variant Initialization and Assignment 624

26.7 Afternotes 628

Chapter 27: Expression Templates 629

27.1 Temporaries and Split Loops 630

27.2 Encoding Expressions in Template Arguments 635

27.3 Performance and Limitations of Expression Templates 646

27.4 Afternotes 647

Chapter 28: Debugging Templates 651

28.1 Shallow Instantiation 652

28.2 Static Assertions 654

28.3 Archetypes 655

28.4 Tracers 657

28.5 Oracles 662

28.6 Afternotes 662

Appendixes 663

Appendix A: The One-Definition Rule 663

A.1 Translation Units 663

A.2 Declarations and Definitions 664

A.3 The One-Definition Rule in Detail 665

Appendix B: Value Categories 673

B.1 Traditional Lvalues and Rvalues 673

B.2 Value Categories Since C++11 674

B.3 Checking Value Categories with decltype 678

B.4 Reference Types 679

Appendix C: Overload Resolution 681

C.1 When Does Overload Resolution Kick In? 681

C.2 Simplified Overload Resolution 682

C.3 Overloading Details 688

Appendix D: Standard Type Utilities 697

D.1 Using Type Traits 697

D.2 Primary and Composite Type Categories 702

D.3 Type Properties and Operations 709

D.4 Type Construction 728

D.5 Other Traits 732

D.6 Combining Type Traits 734

D.7 Other Utilities 737

Appendix E: Concepts 739

E.1 Using Concepts 739

E.2 Defining Concepts 742

E.3 Overloading on Constraints 743

E.4 Concept Tips 746

Bibliography 749

Glossary 759

Index 771

Updates

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020