Professional Documents
Culture Documents
PDF C Templates The Complete Guide Second Edition David Vandevoorde Nicolai M Josuttis Douglas Gregor Ebook Full Chapter
PDF C Templates The Complete Guide Second Edition David Vandevoorde Nicolai M Josuttis Douglas Gregor Ebook Full Chapter
https://textbookfull.com/product/c-17-the-complete-guide-nicolai-
m-josuttis/
https://textbookfull.com/product/c-move-semantics-the-complete-
guide-nicolai-m-josuttis/
https://textbookfull.com/product/primary-mathematics-
textbook-2b-jennifer-hoerst/
https://textbookfull.com/product/handbook-of-macroeconomics-
volume-2a-2b-set-1st-edition-john-b-taylor/
Blender 2D Animation: The Complete Guide to the Grease
Pencil: Second Edition John M. Blain
https://textbookfull.com/product/blender-2d-animation-the-
complete-guide-to-the-grease-pencil-second-edition-john-m-blain/
https://textbookfull.com/product/complete-guide-to-the-national-
park-lodges-david-scott/
https://textbookfull.com/product/electronically-stored-
information-the-complete-guide-to-management-understanding-
acquisition-storage-search-and-retrieval-second-edition-david-r-
matthews/
https://textbookfull.com/product/the-lstas-complete-credit-
agreement-guide-second-edition-michael-bellucci/
https://textbookfull.com/product/complete-guide-to-the-national-
park-lodges-9th-edition-david-scott/
C++ Templates
The Complete Guide
Second Edition
David Vandevoorde
Nicolai M. Josuttis
Douglas Gregor
Preface
Acknowledgments for the Second Edition
Acknowledgments for the First Edition
About This Book
What You Should Know Before Reading This Book
Overall Structure of the Book
How to Read This Book
Some Remarks About Programming Style
The C++11, C++14, and C++17 Standards
Example Code and Additional Information
Feedback
1 Function Templates
1.1 A First Look at Function Templates
1.1.1 Defining the Template
1.1.2 Using the Template
1.1.3 Two-Phase Translation
1.2 Template Argument Deduction
1.3 Multiple Template Parameters
1.3.1 Template Parameters for Return Types
1.3.2 Deducing the Return Type
1.3.3 Return Type as Common Type
1.4 Default Template Arguments
1.5 Overloading Function Templates
1.6 But, Shouldn’t We …?
1.6.1 Pass by Value or by Reference?
1.6.2 Why Not inline?
1.6.3 Why Not constexpr?
1.7 Summary
2 Class Templates
2.1 Implementation of Class Template Stack
2.1.1 Declaration of Class Templates
2.1.2 Implementation of Member Functions
2.2 Use of Class Template Stack
2.3 Partial Usage of Class Templates
2.3.1 Concepts
2.4 Friends
2.5 Specializations of Class Templates
2.6 Partial Specialization
2.7 Default Class Template Arguments
2.8 Type Aliases
2.9 Class Template Argument Deduction
2.10 Templatized Aggregates
2.11 Summary
4 Variadic Templates
4.1 Variadic Templates
4.1.1 Variadic Templates by Example
4.1.2 Overloading Variadic and Nonvariadic Templates
4.1.3 Operator sizeof…
4.2 Fold Expressions
4.3 Application of Variadic Templates
4.4 Variadic Class Templates and Variadic Expressions
4.4.1 Variadic Expressions
4.4.2 Variadic Indices
4.4.3 Variadic Class Templates
4.4.4 Variadic Deduction Guides
4.4.5 Variadic Base Classes and using
4.5 Summary
5 Tricky Basics
5.1 Keyword typename
5.2 Zero Initialization
5.3 Using this->
5.4 Templates for Raw Arrays and String Literals
5.5 Member Templates
5.5.1 The .template Construct
5.5.2 Generic Lambdas and Member Templates
5.6 Variable Templates
5.7 Template Template Parameters
5.8 Summary
8 Compile-Time Programming
8.1 Template Metaprogramming
8.2 Computing with constexpr
8.3 Execution Path Selection with Partial Specialization
8.4 SFINAE (Substitution Failure Is Not An Error)
8.4.1 Expression SFINAE with decltype
8.5 Compile-Time if
8.6 Summary
11 Generic Libraries
11.1 Callables
11.1.1 Supporting Function Objects
11.1.2 Dealing with Member Functions and Additional
Arguments
11.1.3 Wrapping Function Calls
11.2 Other Utilities to Implement Generic Libraries
11.2.1 Type Traits
11.2.2 std::addressof()
11.2.3 std::declval()
11.3 Perfect Forwarding Temporaries
11.4 References as Template Parameters
11.5 Defer Evaluations
11.6 Things to Consider When Writing Generic Libraries
11.7 Summary
12 Fundamentals in Depth
12.1 Parameterized Declarations
12.1.1 Virtual Member Functions
12.1.2 Linkage of Templates
12.1.3 Primary Templates
12.2 Template Parameters
12.2.1 Type Parameters
12.2.2 Nontype Parameters
12.2.3 Template Template Parameters
12.2.4 Template Parameter Packs
12.2.5 Default Template Arguments
12.3 Template Arguments
12.3.1 Function Template Arguments
12.3.2 Type Arguments
12.3.3 Nontype Arguments
12.3.4 Template Template Arguments
12.3.5 Equivalence
12.4 Variadic Templates
12.4.1 Pack Expansions
12.4.2 Where Can Pack Expansions Occur?
12.4.3 Function Parameter Packs
12.4.4 Multiple and Nested Pack Expansions
12.4.5 Zero-Length Pack Expansions
12.4.6 Fold Expressions
12.5 Friends
12.5.1 Friend Classes of Class Templates
12.5.2 Friend Functions of Class Templates
12.5.3 Friend Templates
12.6 Afternotes
13 Names in Templates
13.1 Name Taxonomy
13.2 Looking Up Names
13.2.1 Argument-Dependent Lookup
13.2.2 Argument-Dependent Lookup of Friend Declarations
13.2.3 Injected Class Names
13.2.4 Current Instantiations
13.3 Parsing Templates
13.3.1 Context Sensitivity in Nontemplates
13.3.2 Dependent Names of Types
13.3.3 Dependent Names of Templates
13.3.4 Dependent Names in Using Declarations
13.3.5 ADL and Explicit Template Arguments
13.3.6 Dependent Expressions
13.3.7 Compiler Errors
13.4 Inheritance and Class Templates
13.4.1 Nondependent Base Classes
13.4.2 Dependent Base Classes
13.5 Afternotes
14 Instantiation
14.1 On-Demand Instantiation
14.2 Lazy Instantiation
14.2.1 Partial and Full Instantiation
14.2.2 Instantiated Components
14.3 The C++ Instantiation Model
14.3.1 Two-Phase Lookup
14.3.2 Points of Instantiation
14.3.3 The Inclusion Model
14.4 Implementation Schemes
14.4.1 Greedy Instantiation
14.4.2 Queried Instantiation
14.4.3 Iterated Instantiation
14.5 Explicit Instantiation
14.5.1 Manual Instantiation
14.5.2 Explicit Instantiation Declarations
14.6 Compile-Time if Statements
14.7 In the Standard Library
14.8 Afternotes
17 Future Directions
17.1 Relaxed typename Rules
17.2 Generalized Nontype Template Parameters
17.3 Partial Specialization of Function Templates
17.4 Named Template Arguments
17.5 Overloaded Class Templates
17.6 Deduction for Nonfinal Pack Expansions
17.7 Regularization of void
17.8 Type Checking for Templates
17.9 Reflective Metaprogramming
17.10 Pack Facilities
17.11 Modules
Part III: Templates and Design
19 Implementing Traits
19.1 An Example: Accumulating a Sequence
19.1.1 Fixed Traits
19.1.2 Value Traits
19.1.3 Parameterized Traits
19.2 Traits versus Policies and Policy Classes
19.2.1 Traits and Policies: What’s the Difference?
19.2.2 Member Templates versus Template Template
Parameters
19.2.3 Combining Multiple Policies and/or Traits
19.2.4 Accumulation with General Iterators
19.3 Type Functions
19.3.1 Element Types
19.3.2 Transformation Traits
19.3.3 Predicate Traits
19.3.4 Result Type Traits
19.4 SFINAE-Based Traits
19.4.1 SFINAE Out Function Overloads
19.4.2 SFINAE Out Partial Specializations
19.4.3 Using Generic Lambdas for SFINAE
19.4.4 SFINAE-Friendly Traits
19.5 IsConvertibleT
19.6 Detecting Members
19.6.1 Detecting Member Types
19.6.2 Detecting Arbitrary Member Types
19.6.3 Detecting Nontype Members
19.6.4 Using Generic Lambdas to Detect Members
19.7 Other Traits Techniques
19.7.1 If-Then-Else
19.7.2 Detecting Nonthrowing Operations
19.7.3 Traits Convenience
19.8 Type Classification
19.8.1 Determining Fundamental Types
19.8.2 Determining Compound Types
19.8.3 Identifying Function Types
19.8.4 Determining Class Types
19.8.5 Determining Enumeration Types
19.9 Policy Traits
19.9.1 Read-Only Parameter Types
19.10 In the Standard Library
19.11 Afternotes
23 Metaprogramming
23.1 The State of Modern C++ Metaprogramming
23.1.1 Value Metaprogramming
23.1.2 Type Metaprogramming
23.1.3 Hybrid Metaprogramming
23.1.4 Hybrid Metaprogramming for Unit Types
23.2 The Dimensions of Reflective Metaprogramming
23.3 The Cost of Recursive Instantiation
23.3.1 Tracking All Instantiations
23.4 Computational Completeness
23.5 Recursive Instantiation versus Recursive Template
Arguments
23.6 Enumeration Values versus Static Constants
23.7 Afternotes
24 Typelists
24.1 Anatomy of a Typelist
24.2 Typelist Algorithms
24.2.1 Indexing
24.2.2 Finding the Best Match
24.2.3 Appending to a Typelist
24.2.4 Reversing a Typelist
24.2.5 Transforming a Typelist
24.2.6 Accumulating Typelists
24.2.7 Insertion Sort
24.3 Nontype Typelists
24.3.1 Deducible Nontype Parameters
24.4 Optimizing Algorithms with Pack Expansions
24.5 Cons-style Typelists
24.6 Afternotes
25 Tuples
25.1 Basic Tuple Design
25.1.1 Storage
25.1.2 Construction
25.2 Basic Tuple Operations
25.2.1 Comparison
25.2.2 Output
25.3 Tuple Algorithms
25.3.1 Tuples as Typelists
25.3.2 Adding to and Removing from a Tuple
25.3.3 Reversing a Tuple
25.3.4 Index Lists
25.3.5 Reversal with Index Lists
25.3.6 Shuffle and Select
25.4 Expanding Tuples
25.5 Optimizing Tuple
25.5.1 Tuples and the EBCO
25.5.2 Constant-time get()
25.6 Tuple Subscript
25.7 Afternotes
26 Discriminated Unions
26.1 Storage
26.2 Design
26.3 Value Query and Extraction
26.4 Element Initialization, Assignment and Destruction
26.4.1 Initialization
26.4.2 Destruction
26.4.3 Assignment
26.5 Visitors
26.5.1 Visit Result Type
26.5.2 Common Result Type
26.6 Variant Initialization and Assignment
26.7 Afternotes
27 Expression Templates
27.1 Temporaries and Split Loops
27.2 Encoding Expressions in Template Arguments
27.2.1 Operands of the Expression Templates
27.2.2 The Array Type
27.2.3 The Operators
27.2.4 Review
27.2.5 Expression Templates Assignments
27.3 Performance and Limitations of Expression Templates
27.4 Afternotes
28 Debugging Templates
28.1 Shallow Instantiation
28.2 Static Assertions
28.3 Archetypes
28.4 Tracers
28.5 Oracles
28.6 Afternotes
Appendixes
B Value Categories
B.1 Traditional Lvalues and Rvalues
B.1.1 Lvalue-to-Rvalue Conversions
B.2 Value Categories Since C++11
B.2.1 Temporary Materialization
B.3 Checking Value Categories with decltype
B.4 Reference Types
C Overload Resolution
C.1 When Does Overload Resolution Kick In?
C.2 Simplified Overload Resolution
C.2.1 The Implied Argument for Member Functions
C.2.2 Refining the Perfect Match
C.3 Overloading Details
C.3.1 Prefer Nontemplates or More Specialized Templates
C.3.2 Conversion Sequences
C.3.3 Pointer Conversions
C.3.4 Initializer Lists
C.3.5 Functors and Surrogate Functions
C.3.6 Other Overloading Contexts
E Concepts
E.1 Using Concepts
E.2 Defining Concepts
E.3 Overloading on Constraints
E.3.1 Constraint Subsumption
E.3.2 Constraints and Tag Dispatching
E.4 Concept Tips
E.4.1 Testing Concepts
E.4.2 Concept Granularity
E.4.3 Binary Compatibility
Bibliography
Forums
Books and Web Sites
Glossary
Index
Preface
“Presently the music starts again, and the spirit known as ‘Ngardaddi’ is seen to be
stealthily creeping towards the fire, his body lying flat upon the ground and his legs
dragging behind.”
CHAPTER XXVII
RELIGIOUS IDEAS
1. The median basilic vein is being slit. Note ligature above the biceps.
2. The blood which is spurting from the incision is being collected on a shield.
The men sit in a row at the back of the fire, with their thighs asunder
and their legs bent in the knees; their chins are resting upon their
chests whilst they beat the backs of their heads with small bundles of
brushwood, keeping time with their song and with the performance of
the warrior.
When, after a while, the music ceases, the warrior is seen to be
lying asleep beside his captive. The ancestors become restless and
begin to move sideways, first in a body to the left and then to the
right; then they move backwards and forwards. This movement is
peculiarly weird since the performers do it by shuffling over the
ground in the sitting posture, with their arms held erect, but bent in
the elbow.
Presently the music starts again, and the spirit known as
“Ngardaddi” is seen to be stealthily creeping towards the fire, his
body lying flat upon the ground and his legs dragging behind. He
advances very slowly, turning his face towards the ground, in search
of the fire which escaped from heaven. He wears a tall head-dress
quite thirty-two inches long, which consists of a tightly fitting
hemispherical cap carrying a column in its centre, at the top of which
a bundle of split black-cockatoo feathers is attached. The feathers
are from the male bird’s tail, and the brilliant red patches in them are
representative of fire. The whole structure is made of paper-bark and
human hair-string, the outer surface being decorated with ochre,
pipeclay, charcoal, and vegetable-down. Vide Plate XXXII.
All the time the men at the fire-side are beating time with their
hands and simultaneously turn their heads from side to side, to all
intents and purposes quite unconcerned about the Ngardaddi who is
gradually crawling near to them. This is done to entice the thief
nearer and lead him to believe that he is unobserved. All of a
sudden, however, when the spirit is about to touch the fire and is in
the act of snatching it from the tribesmen, one of the group on either
side of the fire throws a handful of dry grass upon the smouldering
heap. The flame responds immediately and casts a bright light all
around.
Alarm is raised by the tribesmen by clapping their hands together
violently. The spirit collapses and lies flat upon the ground at full
length. Two or three of the men nearest by seize some of the burning
grass and hit the prostrate figure over the head. The spirit jumps to
his feet and treads the ground as if endeavouring to make his
escape. Seeing this, the men at the fire rise quickly and treat their
victim most unmercifully with bundles of burning grass and twigs.
Eventually each of them seizes a fire-brand and digs the burning end
deeply into the spirit’s back and the unfortunate fellow eventually
decamps into the darkness amidst the bellowing whoops of his
victors.
The air is fouled for some distance around by the smell of the
burned skin, reminding one of the stench in a smithy when horses
are being shod. The back of the spirit-impersonator is naturally
severely scored by the cruel treatment it is subjected to, but the
fellow takes it all in good faith and without flinching.
The object of the ceremony is twofold. Firstly all members of the
community who are present, men, women, and children, are taught
to appreciate the value of fire, and secondly it is believed that the
exemplification of so harsh and drastic a treatment for attempted
theft will tend to make abortive any schemes of the evil spirits.
The Arunndta are quite convinced in their own minds that in the
days of their tribal fathers there was no water on the surface of the
ground they occupied; their ancestors in those times were compelled
to live on grass and succulent plants, no consideration being given to
the fact, as we have learned, that the vegetation derives its moisture
from outside sources. But it happened one day, when their
forefathers were out hunting, that they met with a number of strange-
looking men who were sitting around a pool of pure water from which
they were drinking. At the sight of the men, the strangers fled,
leaving the water behind. The hunters gave chase but all except one
disappeared and he made for a cave in the hills. The hunters closed
the mouth of the cave with a big stone and went back to the pool of
water to quench their thirst, but when they reached the spot, the
water had turned into a massive, round stone. The men made back
to the cave and removed the obstruction, but imagine their surprise
when they found the cave empty. Upon making a careful search,
however, they discovered a long cylindrical stick which had some
peculiar markings on it. They took the stick and walked once more
towards the petrified pool, and, lo, they beheld the stranger they
were looking for walking in the sky. When he saw the stick in the
hands of the hunters, he took the form of a cloud, and as he bent his
body towards the stick, his long matted hair fell forwards and from it
water poured upon the earth beneath. The hunters drank freely of
the precious fluid and when they looked skywards again the
cloudman had vanished.
From that day onwards the Arunndta medicine men (“Nangarri”)
have kept that spot sacred and taboo to the women and children;
they call the big stone “Imbodna” which means “the hailstone.” The
man who fled to the cave and then escaped from the hunters as a
vapour they call “Nangali,” the name for a cloud. The tribe has never
since been without water because Nangali left his magic wand in the
hands of their ancient sorcerers and whenever the country was
suffering from drought they could call upon him to appear in the sky
and bring forth rain.
Nangali is one of a group of celestial beings who have been
termed “Atoakwatje,” that is Water-Men; they are now looked upon
as Demigods who control all terrestrial supplies of water from their
abode in the clouds. The Atoakwatje are believed to have certain
mysterious connections with some of the tribal sorcerers who in a
sense parade on earth as their disciples and attend to the rain-
making ceremonies through which they are able to commune with
each other.
When the people are in need of water, the rain-makers assemble
around the Imbodna and one or two of them produce the sacred
stick, known to the Arunndta as “kwatje-purra,” literally meaning “the
reproductive organ of water,” and to the Aluridja as “kapi-wiyinna.”
Nowadays these sticks, which strictly speaking are of phallic
significance, are flat and more like a tjuringa in shape, and have a
number of peculiar markings on them. For a time the stick is laid
beside the great water-stone, and the sorcerers kneel while they
chant with a barely audible voice. They rise to their feet and the most
influential individual who is decorated with stripes of yellow
vegetable-down and wears a dog-tail tassel on his belt, lifts the stick
towards the sky and continues mumbling. The other members kneel
again and all present chat together. The man who is standing poises
the stick horizontally between his hands and rocks it one way, then
another; and this performance is frequently repeated.
When at length the principal performer sits down, the other men
leave the spot and run in a single file towards the camp, loudly crying
“kurreke ta ta” in imitation of the call of the spur-winged plover.
In the evening a general corroboree is indulged in; and all grown-
up persons, male and female, are allowed to join in. Several refrains
are forthcoming which are connected with ordinary rain or water
festivals. The principal rainmaker does not attend but joins the camp
again during the night. It appears that in the interim he has visited
the sacred cave, in company of one or two of his brother-sorcerers,
to hide the magic stick and preserve it for future use. Any
representative of the Atoakwatje group inherits the power to fashion
and use the rain-stick, but it is imperative that he learns the art under
the direction of a senior and duly qualified nangarri.
A ceremony directly connected with sun-worship belongs to the
old Arunndta people and is known as “Ilpalinja.” When the weather
has been and continues to be unpleasantly cold, and the mating
season of birds and animals has on that account been long delayed,
the men construct a large colored design upon the selected
ceremonial ground. Radiating from a point upon a cleared space,
many lines are drawn with red and white vegetable-down to
represent the rays of the sun; and these are intersected at different
distances from the central point by a number of concentric circles
which represent the fathers of the tribe. The centre of the design is
occupied by a stick which is supposed to incorporate some mystical
and sacred sun-creature known as “Knaninja Arrerreka.” The same
Ilpalinja-design is occasionally carved as the crest of the Knaninja
upon a sun-tjuringa. Vide Fig. 6.