Title Page....2
Copyright Page....3
Dedication....5
Contents....6
Preface....24
Acknowledgments for the Second Edition....26
Acknowledgments for the First Edition....29
About This Book....32
What You Should Know Before Reading This Book....33
Overall Structure of the Book....34
How to Read This Book....35
Some Remarks About Programming Style....35
The C++11, C++14, and C++17 Standards....38
Example Code and Additional Information....39
Feedback....40
Part I: The Basics....41
1 Function Templates....43
1.1 A First Look at Function Templates....43
1.1.1 Defining the Template....43
1.1.2 Using the Template....45
1.1.3 Two-Phase Translation....47
1.2 Template Argument Deduction....48
1.3 Multiple Template Parameters....50
1.3.1 Template Parameters for Return Types....51
1.3.2 Deducing the Return Type....53
1.3.3 Return Type as Common Type....55
1.4 Default Template Arguments....56
1.5 Overloading Function Templates....58
1.6 But, Shouldn’t We …?....64
1.6.1 Pass by Value or by Reference?....65
1.6.2 Why Not inline?....65
1.6.3 Why Not constexpr?....66
1.7 Summary....67
2 Class Templates....70
2.1 Implementation of Class Template Stack....70
2.1.1 Declaration of Class Templates....71
2.1.2 Implementation of Member Functions....73
2.2 Use of Class Template Stack....75
2.3 Partial Usage of Class Templates....77
2.3.1 Concepts....78
2.4 Friends....79
2.5 Specializations of Class Templates....81
2.6 Partial Specialization....83
2.7 Default Class Template Arguments....86
2.8 Type Aliases....88
2.9 Class Template Argument Deduction....91
2.10 Templatized Aggregates....96
2.11 Summary....97
3 Nontype Template Parameters....99
3.1 Nontype Class Template Parameters....99
3.2 Nontype Function Template Parameters....102
3.3 Restrictions for Nontype Template Parameters....104
3.4 Template Parameter Type auto....106
3.5 Summary....110
4 Variadic Templates....112
4.1 Variadic Templates....112
4.1.1 Variadic Templates by Example....112
4.1.2 Overloading Variadic and Nonvariadic Templates....114
4.1.3 Operator sizeof…....115
4.2 Fold Expressions....116
4.3 Application of Variadic Templates....119
4.4 Variadic Class Templates and Variadic Expressions....121
4.4.1 Variadic Expressions....121
4.4.2 Variadic Indices....122
4.4.3 Variadic Class Templates....123
4.4.4 Variadic Deduction Guides....124
4.4.5 Variadic Base Classes and using....125
4.5 Summary....127
5 Tricky Basics....128
5.1 Keyword typename....128
5.2 Zero Initialization....130
5.3 Using this->....132
5.4 Templates for Raw Arrays and String Literals....133
5.5 Member Templates....136
5.5.1 The .template Construct....144
5.5.2 Generic Lambdas and Member Templates....144
5.6 Variable Templates....145
5.7 Template Template Parameters....148
5.8 Summary....155
6 Move Semantics and enable_if<>....157
6.1 Perfect Forwarding....157
6.2 Special Member Function Templates....161
6.3 Disable Templates with enable_if<>....165
6.4 Using enable_if<>....167
6.5 Using Concepts to Simplify enable_if<> Expressions....172
6.6 Summary....174
7 By Value or by Reference?....176
7.1 Passing by Value....177
7.2 Passing by Reference....180
7.2.1 Passing by Constant Reference....180
7.2.2 Passing by Nonconstant Reference....182
7.2.3 Passing by Forwarding Reference....184
7.3 Using std::ref() and std::cref()....186
7.4 Dealing with String Literals and Raw Arrays....188
7.4.1 Special Implementations for String Literals and Raw Arrays....190
7.5 Dealing with Return Values....191
7.6 Recommended Template Parameter Declarations....194
7.7 Summary....197
8 Compile-Time Programming....200
8.1 Template Metaprogramming....201
8.2 Computing with constexpr....203
8.3 Execution Path Selection with Partial Specialization....205
8.4 SFINAE (Substitution Failure Is Not An Error)....207
8.4.1 Expression SFINAE with decltype....212
8.5 Compile-Time if....214
8.6 Summary....216
9 Using Templates in Practice....218
9.1 The Inclusion Model....218
9.1.1 Linker Errors....218
9.1.2 Templates in Header Files....221
9.2 Templates and inline....223
9.3 Precompiled Headers....224
9.4 Decoding the Error Novel....226
9.5 Afternotes....237
9.6 Summary....238
10 Basic Template Terminology....239
10.1 “Class Template” or “Template Class”?....239
10.2 Substitution, Instantiation, and Specialization....240
10.3 Declarations versus Definitions....241
10.3.1 Complete versus Incomplete Types....243
10.4 The One-Definition Rule....244
10.5 Template Arguments versus Template Parameters....244
10.6 Summary....246
11 Generic Libraries....248
11.1 Callables....248
11.1.1 Supporting Function Objects....249
11.1.2 Dealing with Member Functions and Additional Arguments....252
11.1.3 Wrapping Function Calls....255
11.2 Other Utilities to Implement Generic Libraries....257
11.2.1 Type Traits....258
11.2.2 std::addressof()....260
11.2.3 std::declval()....261
11.3 Perfect Forwarding Temporaries....262
11.4 References as Template Parameters....263
11.5 Defer Evaluations....267
11.6 Things to Consider When Writing Generic Libraries....269
11.7 Summary....270
Part II: Templates in Depth....272
12 Fundamentals in Depth....273
12.1 Parameterized Declarations....273
12.1.1 Virtual Member Functions....279
12.1.2 Linkage of Templates....280
12.1.3 Primary Templates....282
12.2 Template Parameters....283
12.2.1 Type Parameters....283
12.2.2 Nontype Parameters....284
12.2.3 Template Template Parameters....286
12.2.4 Template Parameter Packs....288
12.2.5 Default Template Arguments....290
12.3 Template Arguments....293
12.3.1 Function Template Arguments....293
12.3.2 Type Arguments....296
12.3.3 Nontype Arguments....296
12.3.4 Template Template Arguments....300
12.3.5 Equivalence....302
12.4 Variadic Templates....304
12.4.1 Pack Expansions....305
12.4.2 Where Can Pack Expansions Occur?....307
12.4.3 Function Parameter Packs....310
12.4.4 Multiple and Nested Pack Expansions....312
12.4.5 Zero-Length Pack Expansions....314
12.4.6 Fold Expressions....315
12.5 Friends....317
12.5.1 Friend Classes of Class Templates....317
12.5.2 Friend Functions of Class Templates....319
12.5.3 Friend Templates....321
12.6 Afternotes....322
13 Names in Templates....326
13.1 Name Taxonomy....326
13.2 Looking Up Names....330
13.2.1 Argument-Dependent Lookup....332
13.2.2 Argument-Dependent Lookup of Friend Declarations....335
13.2.3 Injected Class Names....336
13.2.4 Current Instantiations....338
13.3 Parsing Templates....340
13.3.1 Context Sensitivity in Nontemplates....341
13.3.2 Dependent Names of Types....345
13.3.3 Dependent Names of Templates....348
13.3.4 Dependent Names in Using Declarations....349
13.3.5 ADL and Explicit Template Arguments....352
13.3.6 Dependent Expressions....353
13.3.7 Compiler Errors....356
13.4 Inheritance and Class Templates....356
13.4.1 Nondependent Base Classes....357
13.4.2 Dependent Base Classes....358
13.5 Afternotes....362
14 Instantiation....367
14.1 On-Demand Instantiation....367
14.2 Lazy Instantiation....370
14.2.1 Partial and Full Instantiation....370
14.2.2 Instantiated Components....372
14.3 The C++ Instantiation Model....375
14.3.1 Two-Phase Lookup....375
14.3.2 Points of Instantiation....377
14.3.3 The Inclusion Model....381
14.4 Implementation Schemes....382
14.4.1 Greedy Instantiation....384
14.4.2 Queried Instantiation....386
14.4.3 Iterated Instantiation....388
14.5 Explicit Instantiation....389
14.5.1 Manual Instantiation....390
14.5.2 Explicit Instantiation Declarations....393
14.6 Compile-Time if Statements....394
14.7 In the Standard Library....396
14.8 Afternotes....397
15 Template Argument Deduction....402
15.1 The Deduction Process....402
15.2 Deduced Contexts....405
15.3 Special Deduction Situations....407
15.4 Initializer Lists....409
15.5 Parameter Packs....410
15.5.1 Literal Operator Templates....412
15.6 Rvalue References....413
15.6.1 Reference Collapsing Rules....414
15.6.2 Forwarding References....415
15.6.3 Perfect Forwarding....417
15.6.4 Deduction Surprises....421
15.7 SFINAE (Substitution Failure Is Not An Error)....422
15.7.1 Immediate Context....424
15.8 Limitations of Deduction....426
15.8.1 Allowable Argument Conversions....427
15.8.2 Class Template Arguments....429
15.8.3 Default Call Arguments....429
15.8.4 Exception Specifications....430
15.9 Explicit Function Template Arguments....431
15.10 Deduction from Initializers and Expressions....435
15.10.1 The auto Type Specifier....436
15.10.2 Expressing the Type of an Expression with decltype....442
15.10.3 decltype(auto)....446
15.10.4 Special Situations for auto Deduction....449
15.10.5 Structured Bindings....453
15.10.6 Generic Lambdas....458
15.11 Alias Templates....461
15.12 Class Template Argument Deduction....463
15.12.1 Deduction Guides....464
15.12.2 Implicit Deduction Guides....466
15.12.3 Other Subtleties....469
15.13 Afternotes....473
16 Specialization and Overloading....478
16.1 When “Generic Code” Doesn’t Quite Cut It....478
16.1.1 Transparent Customization....479
16.1.2 Semantic Transparency....481
16.2 Overloading Function Templates....483
16.2.1 Signatures....485
16.2.2 Partial Ordering of Overloaded Function Templates....488
16.2.3 Formal Ordering Rules....489
16.2.4 Templates and Nontemplates....491
16.2.5 Variadic Function Templates....495
16.3 Explicit Specialization....498
16.3.1 Full Class Template Specialization....499
16.3.2 Full Function Template Specialization....503
16.3.3 Full Variable Template Specialization....505
16.3.4 Full Member Specialization....506
16.4 Partial Class Template Specialization....509
16.5 Partial Variable Template Specialization....514
16.6 Afternotes....515
17 Future Directions....518
17.1 Relaxed typename Rules....519
17.2 Generalized Nontype Template Parameters....520
17.3 Partial Specialization of Function Templates....523
17.4 Named Template Arguments....525
17.5 Overloaded Class Templates....526
17.6 Deduction for Nonfinal Pack Expansions....527
17.7 Regularization of void....529
17.8 Type Checking for Templates....530
17.9 Reflective Metaprogramming....533
17.10 Pack Facilities....535
17.11 Modules....536
Part III: Templates and Design....539
18 The Polymorphic Power of Templates....540
18.1 Dynamic Polymorphism....540
18.2 Static Polymorphism....544
18.3 Dynamic versus Static Polymorphism....548
18.4 Using Concepts....550
18.5 New Forms of Design Patterns....553
18.6 Generic Programming....554
18.7 Afternotes....558
19 Implementing Traits....561
19.1 An Example: Accumulating a Sequence....562
19.1.1 Fixed Traits....562
19.1.2 Value Traits....566
19.1.3 Parameterized Traits....571
19.2 Traits versus Policies and Policy Classes....572
19.2.1 Traits and Policies: What’s the Difference?....574
19.2.2 Member Templates versus Template Template Parameters....576
19.2.3 Combining Multiple Policies and/or Traits....578
19.2.4 Accumulation with General Iterators....578
19.3 Type Functions....580
19.3.1 Element Types....581
19.3.2 Transformation Traits....584
19.3.3 Predicate Traits....591
19.3.4 Result Type Traits....595
19.4 SFINAE-Based Traits....598
19.4.1 SFINAE Out Function Overloads....599
19.4.2 SFINAE Out Partial Specializations....604
19.4.3 Using Generic Lambdas for SFINAE....606
19.4.4 SFINAE-Friendly Traits....610
19.5 IsConvertibleT....616
19.6 Detecting Members....620
19.6.1 Detecting Member Types....620
19.6.2 Detecting Arbitrary Member Types....622
19.6.3 Detecting Nontype Members....624
19.6.4 Using Generic Lambdas to Detect Members....629
19.7 Other Traits Techniques....632
19.7.1 If-Then-Else....632
19.7.2 Detecting Nonthrowing Operations....636
19.7.3 Traits Convenience....639
19.8 Type Classification....642
19.8.1 Determining Fundamental Types....643
19.8.2 Determining Compound Types....645
19.8.3 Identifying Function Types....650
19.8.4 Determining Class Types....652
19.8.5 Determining Enumeration Types....653
19.9 Policy Traits....654
19.9.1 Read-Only Parameter Types....655
19.10 In the Standard Library....658
19.11 Afternotes....660
20 Overloading on Type Properties....666
20.1 Algorithm Specialization....667
20.2 Tag Dispatching....669
20.3 Enabling/Disabling Function Templates....671
20.3.1 Providing Multiple Specializations....674
20.3.2 Where Does the EnableIf Go?....676
20.3.3 Compile-Time if....678
20.3.4 Concepts....680
20.4 Class Specialization....681
20.4.1 Enabling/Disabling Class Templates....682
20.4.2 Tag Dispatching for Class Templates....683
20.5 Instantiation-Safe Templates....687
20.6 In the Standard Library....693
20.7 Afternotes....695
21 Templates and Inheritance....697
21.1 The Empty Base Class Optimization (EBCO)....697
21.1.1 Layout Principles....698
21.1.2 Members as Base Classes....701
21.2 The Curiously Recurring Template Pattern (CRTP)....704
21.2.1 The Barton-Nackman Trick....707
21.2.2 Operator Implementations....710
21.2.3 Facades....712
21.3 Mixins....720
21.3.1 Curious Mixins....723
21.3.2 Parameterized Virtuality....723
21.4 Named Template Arguments....725
21.5 Afternotes....729
22 Bridging Static and Dynamic Polymorphism....732
22.1 Function Objects, Pointers, and std::function<>....732
22.2 Generalized Function Pointers....735
22.3 Bridge Interface....738
22.4 Type Erasure....739
22.5 Optional Bridging....740
22.6 Performance Considerations....744
22.7 Afternotes....744
23 Metaprogramming....746
23.1 The State of Modern C++ Metaprogramming....746
23.1.1 Value Metaprogramming....746
23.1.2 Type Metaprogramming....747
23.1.3 Hybrid Metaprogramming....748
23.1.4 Hybrid Metaprogramming for Unit Types....750
23.2 The Dimensions of Reflective Metaprogramming....752
23.3 The Cost of Recursive Instantiation....753
23.3.1 Tracking All Instantiations....755
23.4 Computational Completeness....756
23.5 Recursive Instantiation versus Recursive Template Arguments....757
23.6 Enumeration Values versus Static Constants....758
23.7 Afternotes....759
24 Typelists....762
24.1 Anatomy of a Typelist....762
24.2 Typelist Algorithms....765
24.2.1 Indexing....765
24.2.2 Finding the Best Match....767
24.2.3 Appending to a Typelist....770
24.2.4 Reversing a Typelist....773
24.2.5 Transforming a Typelist....774
24.2.6 Accumulating Typelists....776
24.2.7 Insertion Sort....779
24.3 Nontype Typelists....783
24.3.1 Deducible Nontype Parameters....786
24.4 Optimizing Algorithms with Pack Expansions....787
24.5 Cons-style Typelists....789
24.6 Afternotes....792
25 Tuples....794
25.1 Basic Tuple Design....795
25.1.1 Storage....795
25.1.2 Construction....797
25.2 Basic Tuple Operations....799
25.2.1 Comparison....800
25.2.2 Output....800
25.3 Tuple Algorithms....801
25.3.1 Tuples as Typelists....802
25.3.2 Adding to and Removing from a Tuple....803
25.3.3 Reversing a Tuple....805
25.3.4 Index Lists....806
25.3.5 Reversal with Index Lists....808
25.3.6 Shuffle and Select....810
25.4 Expanding Tuples....814
25.5 Optimizing Tuple....816
25.5.1 Tuples and the EBCO....816
25.5.2 Constant-time get()....821
25.6 Tuple Subscript....822
25.7 Afternotes....825
26 Discriminated Unions....828
26.1 Storage....829
26.2 Design....832
26.3 Value Query and Extraction....836
26.4 Element Initialization, Assignment and Destruction....837
26.4.1 Initialization....838
26.4.2 Destruction....839
26.4.3 Assignment....840
26.5 Visitors....846
26.5.1 Visit Result Type....849
26.5.2 Common Result Type....851
26.6 Variant Initialization and Assignment....854
26.7 Afternotes....858
27 Expression Templates....862
27.1 Temporaries and Split Loops....863
27.2 Encoding Expressions in Template Arguments....868
27.2.1 Operands of the Expression Templates....869
27.2.2 The Array Type....873
27.2.3 The Operators....876
27.2.4 Review....877
27.2.5 Expression Templates Assignments....880
27.3 Performance and Limitations of Expression Templates....882
27.4 Afternotes....883
28 Debugging Templates....887
28.1 Shallow Instantiation....888
28.2 Static Assertions....891
28.3 Archetypes....892
28.4 Tracers....895
28.5 Oracles....900
28.6 Afternotes....901
Appendixes....903
A The One-Definition Rule....903
A.1 Translation Units....903
A.2 Declarations and Definitions....904
A.3 The One-Definition Rule in Detail....906
A.3.1 One-per-Program Constraints....906
A.3.2 One-per-Translation Unit Constraints....909
A.3.3 Cross-Translation Unit Equivalence Constraints....911
B Value Categories....916
B.1 Traditional Lvalues and Rvalues....916
B.1.1 Lvalue-to-Rvalue Conversions....918
B.2 Value Categories Since C++11....918
B.2.1 Temporary Materialization....921
B.3 Checking Value Categories with decltype....923
B.4 Reference Types....924
C Overload Resolution....926
C.1 When Does Overload Resolution Kick In?....927
C.2 Simplified Overload Resolution....928
C.2.1 The Implied Argument for Member Functions....931
C.2.2 Refining the Perfect Match....933
C.3 Overloading Details....935
C.3.1 Prefer Nontemplates or More Specialized Templates....936
C.3.2 Conversion Sequences....936
C.3.3 Pointer Conversions....938
C.3.4 Initializer Lists....939
C.3.5 Functors and Surrogate Functions....943
C.3.6 Other Overloading Contexts....944
D Standard Type Utilities....947
D.1 Using Type Traits....947
D.1.1 std::integral_constant and std::bool_constant....947
D.1.2 Things You Should Know When Using Traits....949
D.2 Primary and Composite Type Categories....949
D.2.1 Testing for the Primary Type Category....950
D.2.2 Test for Composite Type Categories....953
D.3 Type Properties and Operations....954
D.3.1 Other Type Properties....955
D.3.2 Test for Specific Operations....962
D.3.3 Relationships Between Types....968
D.4 Type Construction....970
D.5 Other Traits....973
D.6 Combining Type Traits....975
D.7 Other Utilities....977
E Concepts....979
E.1 Using Concepts....980
E.2 Defining Concepts....983
E.3 Overloading on Constraints....985
E.3.1 Constraint Subsumption....986
E.3.2 Constraints and Tag Dispatching....988
E.4 Concept Tips....989
E.4.1 Testing Concepts....989
E.4.2 Concept Granularity....989
E.4.3 Binary Compatibility....991
Bibliography....1020
Forums....1020
Books and Web Sites....1021
Glossary....1033
Index....1050
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.