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.
Author(s): David Vandevoorde, Nicolai M. Josuttis, Douglas Gregor
Edition: 2nd
Year: 2017
Language: English
Pages: 832
Tags: Programming, C++, Templates, Metaprogramming
Cover......Page 1
Title......Page 4
Copyright......Page 5
Contents......Page 8
Preface......Page 24
Acknowledgments for the Second Edition......Page 26
Doug’s Acknowledgments for the Second Edition......Page 27
Acknowledgments for the First Edition......Page 28
David’s Acknowledgments for the First Edition......Page 29
About This Book......Page 30
Overall Structure of the Book......Page 31
Some Remarks About Programming Style......Page 32
The C++11, C++14, and C++17 Standards......Page 34
Feedback......Page 35
Part I: The Basics......Page 36
1.1.1 Defining the Template......Page 38
1.1.2 Using the Template......Page 39
1.1.3 Two-Phase Translation......Page 41
1.2 Template Argument Deduction......Page 42
1.3 Multiple Template Parameters......Page 44
1.3.1 Template Parameters for Return Types......Page 45
1.3.2 Deducing the Return Type......Page 46
1.3.3 Return Type as Common Type......Page 47
1.4 Default Template Arguments......Page 48
1.5 Overloading Function Templates......Page 50
1.6.2 Why Not inline?......Page 55
1.7 Summary......Page 56
2.1 Implementation of Class Template Stack......Page 58
2.1.1 Declaration of Class Templates......Page 59
2.1.2 Implementation of Member Functions......Page 61
2.2 Use of Class Template Stack......Page 62
2.3.1 Concepts......Page 64
2.4 Friends......Page 65
2.5 Specializations of Class Templates......Page 66
2.6 Partial Specialization......Page 68
2.7 Default Class Template Arguments......Page 71
2.8 Type Aliases......Page 73
2.9 Class Template Argument Deduction......Page 75
2.10 Templatized Aggregates......Page 78
2.11 Summary......Page 79
3.1 Nontype Class Template Parameters......Page 80
3.2 Nontype Function Template Parameters......Page 83
3.3 Restrictions for Nontype Template Parameters......Page 84
3.4 Template Parameter Type auto......Page 85
3.5 Summary......Page 89
4.1.1 Variadic Templates by Example......Page 90
4.1.3 Operator sizeof.........Page 92
4.2 Fold Expressions......Page 93
4.3 Application of Variadic Templates......Page 95
4.4 Variadic Class Templates and Variadic Expressions......Page 96
4.4.1 Variadic Expressions......Page 97
4.4.3 Variadic Class Templates......Page 98
4.4.4 Variadic Deduction Guides......Page 99
4.4.5 Variadic Base Classes and using......Page 100
4.5 Summary......Page 101
5.1 Keyword typename......Page 102
5.2 Zero Initialization......Page 103
5.3 Using this->......Page 105
5.4 Templates for Raw Arrays and String Literals......Page 106
5.5 Member Templates......Page 109
5.5.1 The .templateConstruct......Page 114
5.6 Variable Templates......Page 115
5.7 Template Template Parameters......Page 118
5.8 Summary......Page 124
6.1 Perfect Forwarding......Page 126
6.2 Special Member Function Templates......Page 130
6.3 Disable Templates with enable_if<>......Page 133
6.4 Using enable_if<>......Page 134
6.5 Using Concepts to Simplify enable_if<>Expressions......Page 138
6.6 Summary......Page 139
7. By Value or by Reference?......Page 140
7.1 Passing by Value......Page 141
7.2.1 Passing by Constant Reference......Page 143
7.2.2 Passing by Nonconstant Reference......Page 145
7.2.3 Passing by Forwarding Reference......Page 146
7.3 Using std::ref()and std::cref()......Page 147
7.4 Dealing with String Literals and Raw Arrays......Page 150
7.4.1 Special Implementations for String Literals and Raw Arrays......Page 151
7.5 Dealing with Return Values......Page 152
7.6 Recommended Template Parameter Declarations......Page 153
7.7 Summary......Page 156
8.1 Template Metaprogramming......Page 158
8.2 Computing with constexpr......Page 160
8.3 Execution Path Selection with Partial Specialization......Page 162
8.4 SFINAE (Substitution Failure Is Not An Error)......Page 164
8.4.1 Expression SFINAE with decltype......Page 168
8.5 Compile-Time if......Page 169
8.6 Summary......Page 170
9.1.1 Linker Errors......Page 172
9.1.2 Templates in Header Files......Page 174
9.2 Templates and inline......Page 175
9.3 Precompiled Headers......Page 176
9.4 Decoding the Error Novel......Page 178
9.5 Afternotes......Page 184
9.6 Summary......Page 185
10.1 “Class Template” or “Template Class”?......Page 186
10.2 Substitution, Instantiation, and Specialization......Page 187
10.3 Declarations versus Definitions......Page 188
10.4 The One-Definition Rule......Page 189
10.5 Template Arguments versus Template Parameters......Page 190
10.6 Summary......Page 191
11.1 Callables......Page 192
11.1.1 Supporting Function Objects......Page 193
11.1.2 Dealing with Member Functions and Additional Arguments......Page 195
11.1.3 Wrapping Function Calls......Page 197
11.2.1 Type Traits......Page 199
11.2.3 std::declval()......Page 201
11.4 References as Template Parameters......Page 202
11.5 Defer Evaluations......Page 206
11.6 Things to Consider When Writing Generic Libraries......Page 207
11.7 Summary......Page 208
Part II: Templates in Depth......Page 210
12.1 Parameterized Declarations......Page 212
12.1.2 Linkage of Templates......Page 217
12.1.3 Primary Templates......Page 219
12.2.1 Type Parameters......Page 220
12.2.2 Nontype Parameters......Page 221
12.2.3 Template Template Parameters......Page 222
12.2.4 Template Parameter Packs......Page 223
12.2.5 Default Template Arguments......Page 225
12.3.1 Function Template Arguments......Page 227
12.3.3 Nontype Arguments......Page 229
12.3.4 Template Template Arguments......Page 232
12.3.5 Equivalence......Page 234
12.4 Variadic Templates......Page 235
12.4.1 Pack Expansions......Page 236
12.4.2 Where Can Pack Expansions Occur?......Page 237
12.4.3 Function Parameter Packs......Page 239
12.4.4 Multiple and Nested Pack Expansions......Page 240
12.4.6 Fold Expressions......Page 242
12.5.1 Friend Classes of Class Templates......Page 244
12.5.2 Friend Functions of Class Templates......Page 246
12.6 Afternotes......Page 248
13.1 Name Taxonomy......Page 250
13.2 Looking Up Names......Page 252
13.2.1 Argument-Dependent Lookup......Page 254
13.2.2 Argument-Dependent Lookup of Friend Declarations......Page 255
13.2.3 Injected Class Names......Page 256
13.2.4 Current Instantiations......Page 258
13.3 Parsing Templates......Page 259
13.3.1 Context Sensitivity in Nontemplates......Page 260
13.3.2 Dependent Names of Types......Page 263
13.3.3 Dependent Names of Templates......Page 265
13.3.4 Dependent Names in Using Declarations......Page 266
13.3.6 Dependent Expressions......Page 268
13.4.1 Nondependent Base Classes......Page 271
13.4.2 Dependent Base Classes......Page 272
13.5 Afternotes......Page 275
14.1 On-Demand Instantiation......Page 278
14.2.1 Partial and Full Instantiation......Page 280
14.2.2 Instantiated Components......Page 281
14.3.1 Two-Phase Lookup......Page 284
14.3.2 Points of Instantiation......Page 285
14.3.3 The Inclusion Model......Page 289
14.4 Implementation Schemes......Page 290
14.4.1 Greedy Instantiation......Page 291
14.4.2 Queried Instantiation......Page 292
14.4.3 Iterated Instantiation......Page 294
14.5.1 Manual Instantiation......Page 295
14.5.2 Explicit Instantiation Declarations......Page 297
14.6 Compile-Time ifStatements......Page 298
14.7 In the Standard Library......Page 300
14.8 Afternotes......Page 301
15.1 The Deduction Process......Page 304
15.2 Deduced Contexts......Page 306
15.3 Special Deduction Situations......Page 308
15.4 Initializer Lists......Page 309
15.5 Parameter Packs......Page 310
15.6.1 Reference Collapsing Rules......Page 312
15.6.2 Forwarding References......Page 313
15.6.3 Perfect Forwarding......Page 315
15.6.4 Deduction Surprises......Page 318
15.7 SFINAE (Substitution Failure Is Not An Error)......Page 319
15.7.1 Immediate Context......Page 320
15.8 Limitations of Deduction......Page 321
15.8.1 Allowable Argument Conversions......Page 322
15.8.2 Class Template Arguments......Page 323
15.8.3 Default Call Arguments......Page 324
15.8.4 Exception Specifications......Page 325
15.9 Explicit Function Template Arguments......Page 326
15.10 Deduction from Initializers and Expressions......Page 328
15.10.1 The autoType Specifier......Page 329
15.10.2 Expressing the Type of an Expression with decltype......Page 333
15.10.3 decltype(auto)......Page 336
15.10.4 Special Situations for autoDeduction......Page 338
15.10.5 Structured Bindings......Page 341
15.10.6 Generic Lambdas......Page 344
15.11 Alias Templates......Page 347
15.12 Class Template Argument Deduction......Page 348
15.12.1 Deduction Guides......Page 349
15.12.2 Implicit Deduction Guides......Page 351
15.12.3 Other Subtleties......Page 353
15.13 Afternotes......Page 356
16.1 When “Generic Code” Doesn’t Quite Cut It......Page 358
16.1.1 Transparent Customization......Page 359
16.1.2 Semantic Transparency......Page 360
16.2 Overloading Function Templates......Page 361
16.2.1 Signatures......Page 363
16.2.2 Partial Ordering of Overloaded Function Templates......Page 365
16.2.3 Formal Ordering Rules......Page 366
16.2.4 Templates and Nontemplates......Page 367
16.2.5 Variadic Function Templates......Page 370
16.3.1 Full Class Template Specialization......Page 373
16.3.2 Full Function Template Specialization......Page 377
16.3.4 Full Member Specialization......Page 379
16.4 Partial Class Template Specialization......Page 382
16.5 Partial Variable Template Specialization......Page 386
16.6 Afternotes......Page 387
17. Future Directions......Page 388
17.2 Generalized Nontype Template Parameters......Page 389
17.3 Partial Specialization of Function Templates......Page 391
17.4 Named Template Arguments......Page 393
17.5 Overloaded Class Templates......Page 394
17.6 Deduction for Nonfinal Pack Expansions......Page 395
17.8 Type Checking for Templates......Page 396
17.9 Reflective Metaprogramming......Page 398
17.10 Pack Facilities......Page 400
17.11 Modules......Page 401
Part III: Templates and Design......Page 402
18.1 Dynamic Polymorphism......Page 404
18.2 Static Polymorphism......Page 407
18.3 Dynamic versus Static Polymorphism......Page 410
18.4 Using Concepts......Page 412
18.5 New Forms of Design Patterns......Page 414
18.6 Generic Programming......Page 415
18.7 Afternotes......Page 418
19.1 An Example: Accumulating a Sequence......Page 420
19.1.1 Fixed Traits......Page 421
19.1.2 Value Traits......Page 424
19.2 Traits versus Policies and Policy Classes......Page 429
19.2.1 Traits and Policies: What’s the Difference?......Page 432
19.2.2 Member Templates versus Template Template Parameters......Page 433
19.2.4 Accumulation with General Iterators......Page 434
19.3.1 Element Types......Page 436
19.3.2 Transformation Traits......Page 439
19.3.3 Predicate Traits......Page 445
19.3.4 Result Type Traits......Page 448
19.4.1 SFINAE Out Function Overloads......Page 451
19.4.2 SFINAE Out Partial Specializations......Page 455
19.4.3 Using Generic Lambdas for SFINAE......Page 456
19.4.4 SFINAE-Friendly Traits......Page 459
19.5 IsConvertibleT......Page 463
19.6.1 Detecting Member Types......Page 466
19.6.2 Detecting Arbitrary Member Types......Page 468
19.6.3 Detecting Nontype Members......Page 469
19.6.4 Using Generic Lambdas to Detect Members......Page 473
19.7.1 If-Then-Else......Page 475
19.7.2 Detecting Nonthrowing Operations......Page 478
19.7.3 Traits Convenience......Page 481
19.8.1 Determining Fundamental Types......Page 483
19.8.2 Determining Compound Types......Page 486
19.8.3 Identifying Function Types......Page 489
19.8.4 Determining Class Types......Page 491
19.8.5 Determining Enumeration Types......Page 492
19.9.1 Read-Only Parameter Types......Page 493
19.10 In the Standard Library......Page 496
19.11 Afternotes......Page 497
20.1 Algorithm Specialization......Page 500
20.2 Tag Dispatching......Page 502
20.3 Enabling/Disabling Function Templates......Page 504
20.3.1 Providing Multiple Specializations......Page 506
20.3.2 Where Does the EnableIfGo?......Page 507
20.3.3 Compile-Time if......Page 509
20.3.4 Concepts......Page 510
20.4.1 Enabling/Disabling Class Templates......Page 512
20.4.2 Tag Dispatching for Class Templates......Page 514
20.5 Instantiation-Safe Templates......Page 517
20.6 In the Standard Library......Page 522
20.7 Afternotes......Page 523
21.1 The Empty Base Class Optimization (EBCO)......Page 524
21.1.1 Layout Principles......Page 525
21.1.2 Members as Base Classes......Page 527
21.2 The Curiously Recurring Template Pattern (CRTP)......Page 530
21.2.1 The Barton-Nackman Trick......Page 532
21.2.2 Operator Implementations......Page 535
21.2.3 Facades......Page 536
21.3 Mixins......Page 543
21.3.2 Parameterized Virtuality......Page 545
21.4 Named Template Arguments......Page 547
21.5 Afternotes......Page 550
22.1 Function Objects, Pointers, and std::function<>......Page 552
22.2 Generalized Function Pointers......Page 554
22.3 Bridge Interface......Page 557
22.4 Type Erasure......Page 558
22.5 Optional Bridging......Page 560
22.6 Performance Considerations......Page 562
22.7 Afternotes......Page 563
23.1.1 Value Metaprogramming......Page 564
23.1.2 Type Metaprogramming......Page 566
23.1.3 Hybrid Metaprogramming......Page 567
23.1.4 Hybrid Metaprogramming for Unit Types......Page 569
23.2 The Dimensions of Reflective Metaprogramming......Page 572
23.3 The Cost of Recursive Instantiation......Page 574
23.3.1 Tracking All Instantiations......Page 575
Arguments......Page 577
23.6 Enumeration Values versus Static Constants......Page 578
23.7 Afternotes......Page 580
24.1 Anatomy of a Typelist......Page 584
24.2.1 Indexing......Page 586
24.2.2 Finding the Best Match......Page 587
24.2.3 Appending to a Typelist......Page 590
24.2.4 Reversing a Typelist......Page 592
24.2.5 Transforming a Typelist......Page 594
24.2.6 Accumulating Typelists......Page 595
24.2.7 Insertion Sort......Page 598
24.3 Nontype Typelists......Page 601
24.3.1 Deducible Nontype Parameters......Page 603
24.4 Optimizing Algorithms with Pack Expansions......Page 604
24.5 Cons-style Typelists......Page 606
24.6 Afternotes......Page 608
25. Tuples......Page 610
25.1.1 Storage......Page 611
25.1.2 Construction......Page 613
25.2.1 Comparison......Page 614
25.2.2 Output......Page 615
25.3.1 Tuples as Typelists......Page 616
25.3.2 Adding to and Removing from a Tuple......Page 617
25.3.3 Reversing a Tuple......Page 619
25.3.4 Index Lists......Page 620
25.3.5 Reversal with Index Lists......Page 621
25.3.6 Shuffle and Select......Page 623
25.4 Expanding Tuples......Page 627
25.5.1 Tuples and the EBCO......Page 628
25.5.2 Constant-time get()......Page 633
25.6 Tuple Subscript......Page 634
25.7 Afternotes......Page 636
26. Discriminated Unions......Page 638
26.1 Storage......Page 639
26.2 Design......Page 641
26.3 Value Query and Extraction......Page 645
26.4.1 Initialization......Page 646
26.4.2 Destruction......Page 647
26.4.3 Assignment......Page 648
26.5 Visitors......Page 652
26.5.1 Visit Result Type......Page 656
26.5.2 Common Result Type......Page 657
26.6 Variant Initialization and Assignment......Page 659
26.7 Afternotes......Page 663
27. Expression Templates......Page 664
27.1 Temporaries and Split Loops......Page 665
27.2 Encoding Expressions in Template Arguments......Page 670
27.2.1 Operands of the Expression Templates......Page 671
27.2.2 The ArrayType......Page 674
27.2.3 The Operators......Page 677
27.2.4 Review......Page 678
27.2.5 Expression Templates Assignments......Page 680
27.3 Performance and Limitations of Expression Templates......Page 681
27.4 Afternotes......Page 682
28. Debugging Templates......Page 686
28.1 Shallow Instantiation......Page 687
28.2 Static Assertions......Page 689
28.3 Archetypes......Page 690
28.4 Tracers......Page 692
28.6 Afternotes......Page 697
A.1 Translation Units......Page 698
A.2 Declarations and Definitions......Page 699
A.3.1 One-per-Program Constraints......Page 700
A.3.2 One-per-Translation Unit Constraints......Page 702
A.3.3 Cross-Translation Unit Equivalence Constraints......Page 704
B.1 Traditional Lvalues and Rvalues......Page 708
B.2 Value Categories Since C++11......Page 709
B.2.1 Temporary Materialization......Page 711
B.3 Checking Value Categories with decltype......Page 713
B.4 Reference Types......Page 714
C.1 When Does Overload Resolution Kick In?......Page 716
C.2 Simplified Overload Resolution......Page 717
C.2.1 The Implied Argument for Member Functions......Page 719
C.2.2 Refining the Perfect Match......Page 721
C.3.1 Prefer Nontemplates or More Specialized Templates......Page 723
C.3.3 Pointer Conversions......Page 724
C.3.4 Initializer Lists......Page 726
C.3.5 Functors and Surrogate Functions......Page 729
C.3.6 Other Overloading Contexts......Page 730
D.1 Using Type Traits......Page 732
D.1.1 std::integral_constantand std::bool_constant......Page 733
D.1.2 Things You Should Know When Using Traits......Page 735
D.2.1 Testing for the Primary Type Category......Page 737
D.2.2 Test for Composite Type Categories......Page 741
D.3.1 Other Type Properties......Page 744
D.3.2 Test for Specific Operations......Page 753
D.3.3 Relationships Between Types......Page 760
D.4 Type Construction......Page 763
D.5 Other Traits......Page 767
D.6 Combining Type Traits......Page 769
D.7 Other Utilities......Page 772
E.1 Using Concepts......Page 774
E.2 Defining Concepts......Page 777
E.3 Overloading on Constraints......Page 778
E.3.1 Constraint Subsumption......Page 779
E.3.2 Constraints and Tag Dispatching......Page 780
E.4.2 Concept Granularity......Page 781
E.4.3 Binary Compatibility......Page 782
Forums......Page 784
Books and Web Sites......Page 785
Glossary......Page 794
A......Page 806
B......Page 807
C......Page 808
D......Page 809
E......Page 810
F......Page 811
I......Page 812
L......Page 814
M......Page 815
O......Page 816
P......Page 817
R......Page 818
S......Page 819
T......Page 820
V......Page 822
Z......Page 823