Download full C++ templates: the complete guide Second Edition David Vandevoorde & Nicolai M. Josuttis & Douglas Gregor ebook all chapters

Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

Download the Full Version of textbook for Fast Typing at textbookfull.

com

C++ templates: the complete guide Second Edition


David Vandevoorde & Nicolai M. Josuttis & Douglas
Gregor

https://textbookfull.com/product/c-templates-the-complete-
guide-second-edition-david-vandevoorde-nicolai-m-josuttis-
douglas-gregor/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

C 17 The Complete Guide Nicolai M. Josuttis

https://textbookfull.com/product/c-17-the-complete-guide-nicolai-m-
josuttis/

textboxfull.com

C Move Semantics The Complete Guide Nicolai M. Josuttis

https://textbookfull.com/product/c-move-semantics-the-complete-guide-
nicolai-m-josuttis/

textboxfull.com

Primary Mathematics Textbook 2B Jennifer Hoerst

https://textbookfull.com/product/primary-mathematics-
textbook-2b-jennifer-hoerst/

textboxfull.com

Handbook of Macroeconomics, Volume 2A-2B SET 1st Edition


John B. Taylor

https://textbookfull.com/product/handbook-of-macroeconomics-
volume-2a-2b-set-1st-edition-john-b-taylor/

textboxfull.com
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/

textboxfull.com

Complete Guide to the National Park Lodges David Scott

https://textbookfull.com/product/complete-guide-to-the-national-park-
lodges-david-scott/

textboxfull.com

Electronically Stored Information The Complete Guide to


Management Understanding Acquisition Storage Search and
Retrieval Second Edition David R Matthews
https://textbookfull.com/product/electronically-stored-information-
the-complete-guide-to-management-understanding-acquisition-storage-
search-and-retrieval-second-edition-david-r-matthews/
textboxfull.com

The LSTA's Complete Credit Agreement Guide, Second Edition


Michael Bellucci

https://textbookfull.com/product/the-lstas-complete-credit-agreement-
guide-second-edition-michael-bellucci/

textboxfull.com

Complete Guide to the National Park Lodges 9th Edition


David Scott

https://textbookfull.com/product/complete-guide-to-the-national-park-
lodges-9th-edition-david-scott/

textboxfull.com
C++ Templates
The Complete Guide
Second Edition

David Vandevoorde
Nicolai M. Josuttis
Douglas Gregor

Boston • Columbus • Indianapolis • New York • San Francisco •


Amsterdam • Cape Town Dubai • London • Madrid • Milan • Munich
• Paris • Montreal • Toronto • Delhi • Mexico City São Paulo • Sydney
• Hong Kong • Seoul • Singapore • Taipei • Tokyo
Many of the designations used by manufacturers and sellers to
distinguish their products are claimed as trademarks. Where those
designations appear in this book, and the publisher was aware of a
trademark claim, the designations have been printed with initial
capital letters or in all capitals.
The authors and publisher have taken care in the preparation of this
book, but make no expressed or implied warranty of any kind and
assume no responsibility for errors or omissions. No liability is
assumed for incidental or consequential damages in connection with
or arising out of the use of the information or programs contained
herein.
For information about buying this title in bulk quantities, or for
special sales opportunities (which may include electronic versions;
custom cover designs; and content particular to your business,
training goals, marketing focus, or branding interests), please
contact our corporate sales department at
[email protected] or (800) 382-3419.
For government sales inquiries, please contact
[email protected].
For questions about sales outside the U.S., please contact
[email protected].
Visit us on the Web: informit.com/aw
Library of Congress Catalog Number: 2017946531
Copyright © 2018 Pearson Education, Inc.
This book was typeset by Nicolai M. Josuttis using the LATEX
document processing system. All rights reserved. Printed in the
United States of America. This publication is protected by copyright,
and permission must be obtained from the publisher prior to any
prohibited reproduction, storage in a retrieval system, or
transmission in any form or by any means, electronic, mechanical,
photocopying, recording, or likewise. For information regarding
permissions, request forms and the appropriate contacts within the
Pearson Education Global Rights & Permissions Department, please
visit www.pearsoned.com/permissions/.
ISBN-13: 978-0-321-71412-1
ISBN-10: 0-321-71412-1
1 17
To Alessandra & Cassandra
—David

To those who care for people and mankind


—Nico

To Amy, Tessa & Molly


—Doug
Contents

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

Part I: The Basics

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

3 Nontype Template Parameters


3.1 Nontype Class Template Parameters
3.2 Nontype Function Template Parameters
3.3 Restrictions for Nontype Template Parameters
3.4 Template Parameter Type auto
3.5 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

6 Move Semantics and enable_if<>


6.1 Perfect Forwarding
6.2 Special Member Function Templates
6.3 Disable Templates with enable_if<>
6.4 Using enable_if<>
6.5 Using Concepts to Simplify enable_if<> Expressions
6.6 Summary
7 By Value or by Reference?
7.1 Passing by Value
7.2 Passing by Reference
7.2.1 Passing by Constant Reference
7.2.2 Passing by Nonconstant Reference
7.2.3 Passing by Forwarding Reference
7.3 Using std::ref() and std::cref()
7.4 Dealing with String Literals and Raw Arrays
7.4.1 Special Implementations for String Literals and Raw
Arrays
7.5 Dealing with Return Values
7.6 Recommended Template Parameter Declarations
7.7 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

9 Using Templates in Practice


9.1 The Inclusion Model
9.1.1 Linker Errors
9.1.2 Templates in Header Files
9.2 Templates and inline
9.3 Precompiled Headers
9.4 Decoding the Error Novel
9.5 Afternotes
9.6 Summary
10 Basic Template Terminology
10.1 “Class Template” or “Template Class”?
10.2 Substitution, Instantiation, and Specialization
10.3 Declarations versus Definitions
10.3.1 Complete versus Incomplete Types
10.4 The One-Definition Rule
10.5 Template Arguments versus Template Parameters
10.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

Part II: Templates in Depth

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

15 Template Argument Deduction


15.1 The Deduction Process
15.2 Deduced Contexts
15.3 Special Deduction Situations
15.4 Initializer Lists
15.5 Parameter Packs
15.5.1 Literal Operator Templates
15.6 Rvalue References
15.6.1 Reference Collapsing Rules
15.6.2 Forwarding References
15.6.3 Perfect Forwarding
15.6.4 Deduction Surprises
15.7 SFINAE (Substitution Failure Is Not An Error)
15.7.1 Immediate Context
15.8 Limitations of Deduction
15.8.1 Allowable Argument Conversions
15.8.2 Class Template Arguments
15.8.3 Default Call Arguments
15.8.4 Exception Specifications
15.9 Explicit Function Template Arguments
15.10 Deduction from Initializers and Expressions
15.10.1 The auto Type Specifier
15.10.2 Expressing the Type of an Expression with
decltype
15.10.3 decltype(auto)
15.10.4 Special Situations for auto Deduction
15.10.5 Structured Bindings
15.10.6 Generic Lambdas
15.11 Alias Templates
15.12 Class Template Argument Deduction
15.12.1 Deduction Guides
15.12.2 Implicit Deduction Guides
15.12.3 Other Subtleties
15.13 Afternotes
16 Specialization and Overloading
16.1 When “Generic Code” Doesn’t Quite Cut It
16.1.1 Transparent Customization
16.1.2 Semantic Transparency
16.2 Overloading Function Templates
16.2.1 Signatures
16.2.2 Partial Ordering of Overloaded Function Templates
16.2.3 Formal Ordering Rules
16.2.4 Templates and Nontemplates
16.2.5 Variadic Function Templates
16.3 Explicit Specialization
16.3.1 Full Class Template Specialization
16.3.2 Full Function Template Specialization
16.3.3 Full Variable Template Specialization
16.3.4 Full Member Specialization
16.4 Partial Class Template Specialization
16.5 Partial Variable Template Specialization
16.6 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

18 The Polymorphic Power of Templates


18.1 Dynamic Polymorphism
18.2 Static Polymorphism
18.3 Dynamic versus Static Polymorphism
18.4 Using Concepts
18.5 New Forms of Design Patterns
18.6 Generic Programming
18.7 Afternotes

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

20 Overloading on Type Properties


20.1 Algorithm Specialization
20.2 Tag Dispatching
20.3 Enabling/Disabling Function Templates
20.3.1 Providing Multiple Specializations
20.3.2 Where Does the EnableIf Go?
20.3.3 Compile-Time if
20.3.4 Concepts
20.4 Class Specialization
20.4.1 Enabling/Disabling Class Templates
20.4.2 Tag Dispatching for Class Templates
20.5 Instantiation-Safe Templates
20.6 In the Standard Library
20.7 Afternotes

21 Templates and Inheritance


21.1 The Empty Base Class Optimization (EBCO)
21.1.1 Layout Principles
21.1.2 Members as Base Classes
21.2 The Curiously Recurring Template Pattern (CRTP)
21.2.1 The Barton-Nackman Trick
21.2.2 Operator Implementations
21.2.3 Facades
21.3 Mixins
21.3.1 Curious Mixins
21.3.2 Parameterized Virtuality
21.4 Named Template Arguments
21.5 Afternotes

22 Bridging Static and Dynamic Polymorphism


22.1 Function Objects, Pointers, and std::function<>
22.2 Generalized Function Pointers
22.3 Bridge Interface
22.4 Type Erasure
22.5 Optional Bridging
22.6 Performance Considerations
22.7 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

A The One-Definition Rule


A.1 Translation Units
A.2 Declarations and Definitions
A.3 The One-Definition Rule in Detail
A.3.1 One-per-Program Constraints
A.3.2 One-per-Translation Unit Constraints
A.3.3 Cross-Translation Unit Equivalence Constraints

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

D Standard Type Utilities


D.1 Using Type Traits
D.1.1 std::integral_constant and
std::bool_constant
D.1.2 Things You Should Know When Using Traits
D.2 Primary and Composite Type Categories
D.2.1 Testing for the Primary Type Category
D.2.2 Test for Composite Type Categories
D.3 Type Properties and Operations
D.3.1 Other Type Properties
D.3.2 Test for Specific Operations
D.3.3 Relationships Between Types
D.4 Type Construction
D.5 Other Traits
D.6 Combining Type Traits
D.7 Other Utilities

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

The notion of templates in C++ is over 30 years old. C++ templates


were already documented in 1990 in “The Annotated C++ Reference
Manual” (ARM; see [EllisStroustrupARM]), and they had been
described before then in more specialized publications. However,
well over a decade later, we found a dearth of literature that
concentrates on the fundamental concepts and advanced techniques
of this fascinating, complex, and powerful C++ feature. With the
first edition of this book, we wanted to address this issue and
decided to write the book about templates (with perhaps a slight
lack of humility).
Much has changed in C++ since that first edition was published in
late 2002. New iterations of the C++ standard have added new
features, and continued innovation in the C++ community has
uncovered new template-based programming techniques. The
second edition of this book therefore retains the same goals as the
first edition, but for “Modern C++.”
We approached the task of writing this book with different
backgrounds and with different intentions. David (aka “Daveed”), an
experienced compiler implementer and active participant of the C++
Standard Committee working groups that evolve the core language,
was interested in a precise and detailed description of all the power
(and problems) of templates. Nico, an “ordinary” application
programmer and member of the C++ Standard Committee Library
Working Group, was interested in understanding all the techniques
of templates in a way that he could use and benefit from them.
Doug, a template library developer turned compiler implementer and
language designer, was interested in collecting, categorizing, and
evaluating the myriad techniques used to build template libraries. In
addition, we all wanted to share this knowledge with you, the reader,
and the whole community to help to avoid further misunderstanding,
confusion, or apprehension.
As a consequence, you will see both conceptual introductions with
day-to-day examples and detailed descriptions of the exact behavior
of templates. Starting from the basic principles of templates and
working up to the “art of template programming,” you will discover
(or rediscover) techniques such as static polymorphism, type traits,
metaprogramming, and expression templates. You will also gain a
deeper understanding of the C++ standard library, in which almost
all code involves templates.
We learned a lot and we had much fun while writing this book. We
hope you will have the same experience while reading it. Enjoy!
Acknowledgments for the Second
Edition

Writing a book is hard. Maintaining a book is even harder. It took us


more than five years—spread over the past decade—to come up
with this second edition, and it couldn’t have been done without the
support and patience of a lot of people.
First, we’d like to thank everyone in the C++ community and on
the C++ standardization committee. In addition to all the work to
add new language and library features, they spent many, many
hours explaining and discussing their work with us, and they did so
with patience and enthusiasm.
Part of this community also includes the programmers who gave
feedback for errors and possible improvement for the first edition
over the past 15 years. There are simply too many to list them all,
but you know who you are and we’re truly grateful to you for taking
the time to write up your thoughts and observations. Please accept
our apologies if our answers were sometimes less than prompt.
We’d also like to thank everyone who reviewed drafts of this book
and provided us with valuable feedback and clarifications. These
reviews brought the book to a significantly higher level of quality,
and it again proved that good things need the input of many “wise
guys.” For this reason, huge thanks to Steve Dewhurst, Howard
Hinnant, Mikael Kilpel¨ainen, Dietmar Kühl, Daniel Krügler, Nevin
Lieber, Andreas Neiser, Eric Niebler, Richard Smith, Andrew Sutton,
Hubert Tong, and Ville Voutilainen.
Of course, thanks to all the people who supported us from
Addison-Wesley/Pearson. These days, you can no longer take
professional support for book authors for granted. But they were
patient, nagged us when appropriate, and were of great help when
knowledge and professionalism were necessary. So, many thanks to
Peter Gordon, Kim Boedigheimer, Greg Doench, Julie Nahil, Dana
Wilson, and Carol Lallier.
A special thanks goes to the LaTeX community for a great text
system and to Frank Mittelbach for solving our LATEX issues (it was
almost always our fault).

David’s Acknowledgments for the Second


Edition
This second edition was a long time in the waiting, and as we put
the finishing touches to it, I am grateful for the people in my life
who made it possible despite many obligations vying for attention.
First, I’m indebted to my wife (Karina) and daughters (Alessandra
and Cassandra), for agreeing to let me take significant time out of
the “family schedule” to complete this edition, particularly in the last
year of work. My parents have always shown interest in my goals,
and whenever I visit them, they do not forget this particular project.
Clearly, this is a technical book, and its contents reflect knowledge
and experience about a programming topic. However, that is not
enough to pull off completing this kind of work. I’m therefore
extremely grateful to Nico for having taken upon himself the
“management” and “production” aspects of this edition (in addition
to all of his technical contributions). If this book is useful to you and
you run into Nico some day, be sure to tell him thanks for keeping us
all going. I’m also thankful to Doug for having agreed to come on
board several years ago and to keep going even as demands on his
own schedule made for tough going.
Many programmers in our C++ community have shared nuggets
of insight over the years, and I am grateful to all of them. However,
I owe special thanks to Richard Smith, who has been efficiently
answering my e-mails with arcane technical issues for years now. In
the same vein, thanks to my colleagues John Spicer, Mike Miller, and
Mike Herrick, for sharing their knowledge and creating an
encouraging work environment that allows us to learn ever more.

Nico’s Acknowledgments for the Second


Edition
First, I want to thank the two hard-core experts, David and Doug,
because, as an application programmer and library expert, I asked
so many silly questions and learned so much. I now feel like
becoming a core expert (only until the next issue, of course). It was
fun, guys.
All my other thanks go to Jutta Eckstein. Jutta has the wonderful
ability to force and support people in their ideals, ideas, and goals.
While most people experience this only occasionally when meeting
her or working with her in our IT industry, I have the honor to
benefit from her in my day-to-day life. After all these years, I still
hope this will last forever.

Doug’s Acknowledgments for the Second


Edition
My heartfelt thanks go to my wonderful and supportive wife, Amy,
and our two little girls, Molly and Tessa. Their love and
companionship bring me daily joy and the confidence to tackle the
greatest challenges in life and work. I’d also like to thank my
parents, who instilled in me a great love of learning and encouraged
me throughout these years.
It was a pleasure to work with both David and Nico, who are so
different in personality yet complement each other so well. David
brings a great clarity to technical writing, honing in on descriptions
that are precise and illuminating. Nico, beyond his exceptional
organizational skills that kept two coauthors from wandering off into
the weeds, brings a unique ability to take apart a complex technical
discussion and make it simpler, more accessible, and far, far clearer.
Another Random Scribd Document
with Unrelated Content
The Water of Life
Long before you or I were born, there reigned, in a country a great
way off, a king who had three sons. This king once fell very ill,—so ill
that nobody thought he could live. His sons were very much grieved
at their father’s sickness; and as they were walking together very
mournfully in the garden of the palace, a little old man met them
and asked what was the matter. They told him that their father was
very ill, and that they were afraid nothing could save him. “I know
what would,” said the little old man; “it is the Water of Life. If he
could have a draught of it he would be well again; but it is very hard
to get.” Then the eldest son said, “I will soon find it”: and he went to
the sick king, and begged that he might go in search of the Water of
Life, as it was the only thing that could save him. “No,” said the king,
“I had rather die than place you in such great danger as you must
meet with in your journey.” But he begged so hard that the king let
him go; and the prince thought to himself, “if I bring my father this
water, he will make me sole heir to his kingdom.”
Then he set out: and when he had gone on his way some time he
came to a deep valley, overhung with rocks and woods; and as he
looked around, he saw standing above him on one of the rocks a
little ugly dwarf, with a sugarloaf cap and a scarlet cloak; and the
dwarf called to him and said, “Prince, whither so fast?” “What is that
to thee, you ugly imp?” said the prince haughtily, and rode on.
But the dwarf was enraged at his behaviour, and laid a fairy spell
of ill-luck upon him; so that as he rode on the mountain pass
became narrower and narrower, and at last the way was so
straightened that he could not go a step forward: and when he
thought to have turned his horse round and go back the way he
came, he heard a loud laugh ringing round him, and found that the
path was closed behind him, so that he was shut in all round. He
next tried to get off his horse and make his way on foot, but again
the laugh rang in his ears, and he found himself unable to move a
step, and thus he was forced to abide spellbound.
Meantime the old king was lingering on in daily hope of his son’s
return, till at last the second son said, “Father, I will go in search of
the Water of Life.” For he thought to himself, “My brother is surely
dead, and the kingdom will fall to me if I find the water.” The king
was at first very unwilling to let him go, but at last yielded to his
wish. So he set out and followed the same road which his brother
had done, and met with the same little elf, who stopped him at the
same spot in the mountains, saying, as before, “Prince, prince,
whither so fast?” “Mind your own affairs, busy-body!” said the
prince, scornfully, and rode on.
But the dwarf put the same spell upon him as he had put on his
elder brother; and he, too, was at last obliged to take up his abode
in the heart of the mountains. Thus it is with proud, silly people,
who think themselves above every one else, and are too proud to
ask or take advice.
When the second prince had thus been gone a long time, the
youngest son said he would go and search for the Water of Life, and
trusted he should soon be able to make his father well again. So he
set out, and the dwarf met him too at the same spot in the valley,
among the mountains, and said, “Prince, whither so fast?” And the
prince said, “I am going in search of the Water of Life; because my
father is ill, and like to die: can you help me? Pray be kind, and aid
me if you can!” “Do you know where it is to be found?” asked the
dwarf. “No,” said the prince, “I do not. Pray tell me if you know.”
“Then as you have spoken to me kindly, and are wise enough to
seek for advice, I will tell you how and where to go. The water you
seek springs from a well in an enchanted castle; and, that you may
be able to reach it in safety, I will give you an iron wand and two
little loaves of bread; strike the iron door of the castle three times
with the wand, and it will open: two hungry lions will be lying down
inside gaping for their prey, but if you throw them the bread they
will let you pass; then hasten on to the well, and take some of the
Water of Life before the clock strikes twelve; for if you tarry longer
the door will shut upon you for ever.”
Then the prince thanked his little friend with the scarlet cloak for
his friendly aid; and took the wand and the bread, and went
travelling on and on, over sea and over land, till he came to his
journey’s end, and found everything to be as the dwarf had told him.
The door flew open at the third stroke of the wand, and when the
lions were quieted he went on through the castle and came at length
to a beautiful hall. Around it he saw several knights sitting in a
trance; then he pulled off their rings and put them on his own
fingers. In another room he saw on a table a sword and a loaf of
bread, which he also took. Further on he came to a room where a
beautiful young lady sat upon a couch; and she welcomed him
joyfully, and said, if he would set her free from the spell that bound
her, the kingdom should be his, if he would come back in a year and
marry her. Then she told him that the well that held the Water of
Life was in the palace gardens; and bade him make haste, and draw
what he wanted before the clock struck twelve.
He went on; and as he walked through beautiful gardens, he came
to a delightful shady spot in which stood a couch; and he thought to
himself, as he felt tired, that he would rest himself for awhile, and
gaze on the lovely scenes around him. So he laid himself down, and
sleep fell upon him unawares, so that he did not wake up till the
clock was striking a quarter to twelve. Then he sprang from the
couch dreadfully frightened, ran to the well, filled a cup that was
standing by him full of water, and hastened to get away in time. Just
as he was going out of the iron door it struck twelve, and the door
fell so quickly upon him that it snapt off a piece of his heel.
When he found himself safe, he was overjoyed to think that he
had got the Water of Life; and as he was going on his way
homewards, he passed by the little dwarf, who, when he saw the
sword and the loaf, said, “You have made a noble prize; with the
sword you can at a blow slay whole armies, and the bread will never
fail you.” Then the prince thought to himself, “I cannot go home to
my father without my brothers”; so he said, “My dear friend, cannot
you tell me where my two brothers are, who set out in search of the
Water of Life before me, and never came back?” “I have shut them
up by a charm between two mountains,” said the dwarf, “because
they were proud and ill-behaved, and scorned to ask advice.” The
prince begged so hard for his brothers, that the dwarf at last set
them free, though unwillingly, saying, “Beware of them, for they
have bad hearts.” Their brother, however, was greatly rejoiced to see
them, and told them all that had happened to him; how he had
found the Water of Life, and had taken a cup full of it; and how he
had set a beautiful princess free from a spell that bound her; and
how she had engaged to wait a whole year, and then to marry him,
and to give him the kingdom.
Then they all three rode on together, and on their way home came
to a country that was laid waste by war and a dreadful famine, so
that it was feared all must die for want. But the prince gave the king
of the land the bread, and all his kingdom ate of it. And he lent the
king the wonderful sword, and he slew the enemy’s army with it;
and thus the kingdom was once more in peace and plenty. In the
same manner he befriended two other countries through which they
passed on their way.
When they came to the sea, they got into a ship; and during their
voyage the two eldest said to themselves, “Our brother has got the
water which we could not find, therefore our father will forsake us
and give him the kingdom, which is our right”; so they were full of
envy and revenge, and agreed together how they could ruin him.
Then they waited till he was fast asleep, and poured the Water of
Life out of the cup, and took it for themselves, giving him bitter sea-
water instead.
When they came to their journey’s end, the youngest son brought
his cup to the sick king, that he might drink and be healed. Scarcely,
however, had he tasted the bitter sea-water when he became worse
even than he was before; and then both the elder sons came in, and
blamed the youngest for what he had done; and said that he wanted
to poison their father, but that they had found the Water of Life, and
had brought it with them. He no sooner began to drink of what they
brought him, than he felt his sickness leave him, and was as strong
and well as in his younger days. Then they went to their brother,
and laughed at him, and said, “Well, brother, you found the Water of
Life, did you? You have had the trouble and we shall have the
reward. Pray, with all your cleverness, why did not you manage to
keep your eyes open? Next year one of us will take away your
beautiful princess, if you do not take care. You had better say
nothing about this to our father, for he does not believe a word you
say; and if you tell tales, you shall lose your life into the bargain: but
be quiet, and we will let you off.”
The old king was still very angry with his youngest son, and
thought that he really meant to have taken away his life; so he
called his court together, and asked what should be done, and all
agreed that he ought to be put to death. The prince knew nothing of
what was going on, till one day, when the king’s chief huntsman
went a-hunting with him, and they were alone in the wood together,
the huntsman looked so sorrowful that the prince said, “My friend,
what is the matter with you?” “I cannot and dare not tell you,” said
he. But the prince begged very hard, and said, “Only tell me what it
is, and do not think I shall be angry, for I will forgive you.” “Alas!”
said the huntsman, “the king has ordered me to shoot you.” The
prince started at this, and said, “Let me live, and I will change
dresses with you; you shall take my royal coat to show to my father,
and do you give me your shabby one.” “With all my heart,” said the
huntsman; “I am sure I shall be glad to save you, for I could not
have shot you.” Then he took the prince’s coat, and gave him the
shabby one, and went away through the wood.
Some time after, three grand embassies came to the old king’s
court, with rich gifts of gold and precious stones for his youngest
son; now all these were sent from the three kings to whom he had
lent his sword and loaf of bread, in order to rid them of their enemy
and feed their people. This touched the old king’s heart, and he
thought his son might still be guiltless, and said to his court, “O that
my son were still alive! how it grieves me that I had him killed!” “He
is still alive,” said the huntsman; “and I am glad that I had pity on
him, and saved him: for when the time came, I could not shoot him,
but let him go in peace, and brought home his royal coat.” At this
the king was overwhelmed with joy, and made it known throughout
all his kingdom, that if his son would come back to his court he
would forgive him.
Meanwhile the princess was eagerly waiting till her deliverer
should come back; and had a road made leading up to her palace all
of shining gold; and told her courtiers that whoever came on
horseback, and rode straight up to the gate upon it, was her true
lover; and that they must let him in: but whoever rode on one side
of it, they must be sure was not the right one; and that they must
send him away at once.
The time soon came, when the eldest brother thought that he
would make haste to go to the princess, and say that he was the
one who had set her free, and that he should have her for his wife,
and the kingdom with her. As he came before the palace and saw
the golden road, he stopped to look at it, and he thought to himself,
“It is a pity to ride upon this beautiful road”; so he turned aside and
rode on the right-hand side of it. But when he came to the gate, the
guards, who had seen the road he took, said to him, he could not be
what he said he was, and must go about his business.
The second prince set out soon afterwards on the same errand;
and when he came to the golden road, and his horse had set one
foot upon it, he stopped to look at it, and thought it very beautiful,
and said to himself, “What a pity it is that anything should tread
here!” Then he too turned aside and rode on the left side of it. But
when he came to the gate the guards said he was not the true
prince, and that he too must go away about his business; and away
he went.
Now when the full year was come round, the third brother left the
forest in which he had lain hid for fear of his father’s anger, and set
out in search of his betrothed bride. So he journeyed on, thinking of
her all the way, and rode so quickly that he did not even see what
the road was made of, but went with his horse straight over it; and
as he came to the gate it flew open, and the princess welcomed him
with joy, and said he was her deliverer, and should now be her
husband and lord of the kingdom. When the first joy at their
meeting was over, the princess told him she had heard of his father
having forgiven him, and of his wish to have him home again: so,
before his wedding with the princess, he went to visit his father,
taking her with him. Then he told him everything; how his brothers
had cheated and robbed him, and yet that he had borne all these
wrongs for the love of his father. And the old king was very angry,
and wanted to punish his wicked sons; but they made their escape,
and got into a ship and sailed away over the wide sea, and where
they went to nobody knew and nobody cared.
And now the old king gathered together his
court, and asked all his kingdom to come and
celebrate the wedding of his son and the
princess. And young and old, noble and
squire, gentle and simple, came at once on
the summons; and among the rest came the
friendly dwarf, with the sugarloaf hat, and a
new scarlet cloak.

“And the wedding was held, and the merry bells rung,
And all the good people they danced and they sung,
And feasted and frolick’d I can’t tell how long.”

A Dwarf from Sweden was the next to be invited to the stool, and
sitting down he began to tell how a troll was enabled to do a kindly
service to a poor lad who had saved him from a fierce werewolf.
“My story,” he said, “shall be called
The Troll’s Hammer
There was once a great famine in the country; the poor could not
procure the necessaries of life, and even the rich suffered great
privation. At that time a poor peasant dwelt out on the heath. One
day he said to his son, that he could no longer support him, and that
he must go out in the world, and provide for himself. Niels,
therefore, left home and wandered forth.
Towards evening he found himself in a large forest, and climbed
up into a tree, lest the wild beasts might do him harm during the
night. When he had slept about an hour or perhaps more, a little
man came running towards the tree. He was hunch-backed, had
crooked legs, a long beard, and a red cap on his head. He was
pursued by a werewolf, which attacked him just under the tree in
which Niels was sitting. The little man began to scream; he bit and
scratched, and defended himself as well as he could, but all to no
purpose, the werewolf was his master, and would have torn him in
pieces, if Niels had not sprung down from the tree, and come to his
assistance. As soon as the werewolf saw that he had two to contend
with, he was afraid, and fled back into the forest.
The Troll then said to Niels: “Thou hast preserved my life, and
done me good service; in return I will also give thee something that
will be beneficial to thee. See! here is a hammer, and all the smith’s
work which thou doest with it, no one shall be able to equal.
Continue thy way, and things will go better than thou thinkest.”
When the Troll had spoken these words, he sank into the ground
before Niels.
The next day the boy wandered on, until he came to the
neighbourhood of the royal palace, and here he engaged himself to
a smith.
Now it just happened, that a few days previously a thief had
broken into the king’s treasury and stolen a large bag of money. All
the smiths in the city were, therefore, sent for to the palace, and the
king promised that he who could make the best and securest lock,
should be appointed court locksmith, and have a considerable
reward into the bargain. But the lock must be finished in eight days,
and so constructed that it could not be picked by any one.
When the smith, with whom Niels lived, returned home and
related this, the boy thought he should like to try whether his
hammer really possessed those qualities which the Troll had said. He
therefore begged his master to allow him to make a lock, and
promised that it should be finished by the appointed time. Although
the smith had no great opinion of the boy’s ability, he, nevertheless,
allowed him to make the trial. Niels then requested to have a
separate workshop, locked himself in, and then began hammering
the iron. One day went, and then another, and the master began to
be inquisitive; but Niels let no one come in, and the smith was
obliged to remain outside, and peep through the key-hole. The work,
however, succeeded far better than the boy himself had expected;
and, without his really knowing how it came to pass, the lock was
finished on the evening of the third day.
The following morning he went down to his master and asked him
for some money. “Yesterday I worked hard,” said he, “and to-day I
will make myself merry.” Hereupon he went out of the city, and did
not return to the workshop till late in the evening. The next day he
did the same, and idled away the rest of the week. His master was,
consequently, very angry, and threatened to turn him away, unless
he finished his work at the appointed time. But Niels told him to be
quite easy, and engaged that his lock should be the best. When the
day arrived, Niels brought his work forth, and carried it up to the
palace, and it appeared that his lock was so ingenious and delicately
made, that it far excelled all the others. The consequence was, that
Niels’ master was acknowledged as the most skilful, and received the
promised office and reward.
The smith was delighted, but he took good care not to confess to
any one who it was that had made the curious lock. He now received
one work after another from the king, and let Niels do them all, and
he soon became a wealthy man.
In the meantime, the report spread from place to place of the
ingenious lock the king had got for his treasury. Travellers came from
a great distance to see it, and it happened that a foreign king came
also to the palace. When he had examined the work for a long time,
he said, that the man who could make such a lock deserved to be
honoured and respected. “But however good a smith he may be,”
added the king, “I have got his master at home.” He continued
boasting in this manner, till at length the king offered to wager with
him which could execute the most skilful piece of workmanship. The
smiths were sent for, and the two kings determined that each smith
should make a knife. He who won was to have a considerable
reward. The smith related to Niels what had passed, and desired him
to try whether he could not make as good a knife as he had a lock.
Niels promised that he would, although his last work had not
benefited him much. The smith was in truth an avaricious man, and
treated him so niggardly, that at times he had not enough to eat and
drink.
It happened one day, as Niels was gone out to buy steel to make
the knife, that he met a man from his own village, and, in the course
of conversation, learnt from him that his father went begging from
door to door, and was in great want and misery. When Niels heard
this he asked his master for some money to help his father; but his
master answered, that he should not have a shilling before he had
made the knife. Hereupon Niels shut himself up in the workshop,
worked a whole day, and, as on the former occasion, the knife was
made without his knowing how it happened.
When the day arrived on which the work was to be exhibited,
Niels dressed himself in his best clothes, and went with his master
up to the palace, where the two kings were expecting them. The
strange smith first showed his knife. It was so beautiful, and so
curiously wrought, that it was a pleasure to look at it; it was,
moreover, so sharp and well tempered, that it could cut through a
millstone to the very centre, as if it had been only a cheese, and that
without the edge being in the least blunted. Niels’ knife, on the
contrary, looked very poor and common. The king already began to
think he had lost his wager, and spoke harshly to the master-smith,
when his boy begged leave to examine the stranger’s knife a little
more closely. After having looked at it for some time, he said: “This
is a beautiful piece of workmanship which you have made, and
shame on those who would say otherwise; but my master is,
nevertheless, your superior, as you shall soon experience.” Saying
this, he took the stranger’s knife and split it lengthwise from the
point to the handle with his own knife, as easily as one splits a twig
of willow. The kings could scarcely believe their eyes; and the
consequence was, that the Danish smith was declared the victor, and
got a large bag of money to carry home with him.
When Niels asked for payment, his master refused to give him
anything, although he well knew that the poor boy only wanted the
money to help his father. Upon this Niels grew angry, went up to the
king, and related the whole story to him, how it was he who had
made both the lock and the knife. The master was now called, but
he denied everything, and accused Niels of being an idle boy, whom
he had taken into his service out of charity and compassion.
“The truth of this story we shall soon find out,” said the king, who
sided with the master. “Since thou sayest it is thou who hast made
this wonderful knife, and thy master says it is he who has done it, I
will adjudge each of you to make a sword for me within eight days.
He who can make the most perfect one shall be my master-smith;
but he who loses, shall forfeit his life.”
Niels was well satisfied with this agreement. He went home,
packed up all his things, and bade his master farewell. The smith
was now in great straits, and would gladly have made all good
again; but Niels appeared not to understand him, and went his way,
and engaged with another master, where he cheerfully began to
work on the sword.
When the appointed day arrived, they both met at the palace, and
the master produced a sword of the most elaborate workmanship
that any one could wish to see, besides being inlaid with gold, and
set with precious stones. The king was greatly delighted with it.
“Now, little Niels,” said he, “what dost thou say to this sword?”
“Certainly,” answered the boy, “it is not so badly made as one
might expect from such a bungler.”
“Canst thou show anything like it?” asked the king.
“I believe I can,” answered Niels.
“Well, produce thy sword; where is it?” said the king.
“I have it in my waistcoat pocket,” replied Niels.
Hereupon there was a general laugh, which was increased when
they saw the boy take a little packet out of his waistcoat pocket.
Niels opened the paper, in which the blade was rolled up like a
watch-spring. “Here is my work,” said he, “will you just cut the
thread, master?”
The smith did it willingly, and in a moment the blade straightened
itself and struck him in the face.
Niels took out of his other pocket a hilt of gold, and screwed it fast
to the blade; then presented the sword to the king; and all present
were obliged to confess that they never before had seen such
matchless workmanship.
Niels was unanimously declared the victor, and the master was
obliged to acknowledge that the boy had made both the lock and
the knife.

The king in his indignation would have had the master executed, if
the boy had not begged for mercy on the culprit. Niels received a
handsome reward from the king, and from that day all the work
from the palace was intrusted to him. He took his old father to
reside with him, and lived in competence and happiness till his
death.

When the Swedish Troll had gone back to his place after telling
with much self-satisfaction how one of his fellows had befriended the
poor apprentice, a Norwegian fairy came forward to tell how three of
her companions had similarly served a young princess, and she
named her story
The three little Crones, each with
Something big
There was once a king’s son and a king’s daughter who dearly loved
each other. The young princess was good and fair, and well spoken
of by all, but her disposition was more inclined to pleasure and
dissipation than to handiworks and domestic occupations. To the old
queen this appeared very wrong, and she said she would have no
one for a daughter-in-law that was not as skilled in such matters as
she herself had been in her youth. She therefore opposed the
prince’s marriage in all sorts of ways.
As the queen would not recall her words, the prince went to her
and said, it would be well to make a trial whether the princess were
not as skilful as the queen herself. This seemed to every one a very
rash proposal, seeing that the prince’s mother was a very diligent,
laborious person, and span and sewed and wove both night and day,
so that no one ever saw her like. The prince, however, carried his
point; the fair princess was sent into the maiden’s bower, and the
queen sent her a pound of flax to spin. But the flax was to be spun
ere dawn of day, otherwise the damsel was never more to think of
the prince for a husband.
When left alone the princess found herself very ill at ease; for she
well knew that she could not spin the queen’s flax, and yet trembled
at the thought of losing the prince, who was so dear to her. She
therefore wandered about the apartment and wept, incessantly
wept. At this moment the door was opened very softly, and there
stepped in a little, little woman of singular appearance and yet more
singular manners. The little woman had enormously large feet, at
which every one who saw her must be wonderstruck. She greeted
the princess with: “Peace be with you!” “And peace with you!”
answered the princess. The old woman then asked: “Why is the fair
damsel so sorrowful to-night?” The princess answered: “I may well
be sorrowful. The queen has commanded me to spin a pound of
flax: if I have not completed it before dawn, I lose the young prince
whom I love so dearly.” The old woman then said: “Be of good
cheer, fair maiden; if there is nothing else, I can help you; but then
you must grant me a request which I will name.” At these words the
princess was overjoyed, and asked what it was the old woman
desired. “I am called,” she said, “Mother Bigfoot; and I require for
my aid no other reward than to be present at your wedding. I have
not been at a wedding since the queen your mother-in-law stood as
bride.” The princess readily granted her desire, and they parted. The
princess then lay down to sleep, but could not close her eyes the
whole livelong night.
Early in the morning, before dawn, the door was opened, and the
little woman again entered. She approached the king’s daughter and
handed to her a bundle of yarn, as white as snow and as fine as a
cobweb, saying, “See! such beautiful yarn I have not spun since I
span for the queen, when she was about to be married; but that was
long, long ago.” Having so spoken the little woman disappeared, and
the princess fell into a refreshing slumber, but she had not slept long
when she was awakened by the old queen, who was standing by her
bed, and who asked her whether the flax were all spun. The
princess said that it was, and handed the yarn to her. The queen
must needs appear content, but the princess could not refrain from
observing that her apparent satisfaction did not proceed from good-
will.
Before the day was over, the queen said she would put the
princess to yet another proof. For this purpose she sent the yarn to
the maiden-bower together with a yarn-roll and other implements,
and ordered the princess to weave it into a web; but which must be
ready before sunrise; if not, the damsel must never more think of
the young prince.
When the princess was alone, she again felt sad at heart; for she
knew that she could not weave the queen’s yarn, and yet less
reconcile herself to the thought of losing the prince to whom she
was so dear. She therefore wandered about the apartment and wept
bitterly. At that moment the door was opened softly, softly, and in
stepped a very little woman, of singular figure and still more singular
manners. The little woman had an enormously large back, so that
every one who saw her must be struck with astonishment. She, too,
greeted the princess with: “Peace be with you!” and received for
answer: “Peace with you!” The old woman said: “Why is the fair
damsel so sad and sorrowful?” “I may well be sorrowful,” answered
the princess. “The queen has commanded me to weave all this yarn
into a web; and if I have not completed it by the morning before
sunrise, I shall lose the prince, who loves me so dearly.” The woman
then said: “Be comforted, fair damsel; if it is nothing more, I will
help you. But then you must consent to one condition, which I will
name to you.” At these words the princess was highly delighted, and
asked what the condition might be. “I am called Mother Bigback,
and I desire no other reward than to be at your wedding. I have not
been to any wedding since the queen your mother-in-law stood as
bride.” The king’s daughter readily granted this request, and the little
woman departed. The princess then lay down to sleep, but was
unable to close her eyes the whole night.
In the morning, before daybreak, the door was opened and the
little woman entered. She approached the princess, and handed to
her a web white as snow and close as a skin, so that its like was
never seen. The old woman said: “See! such even threads I have
never woven since I wove for the queen, when she was about to be
married; but that was long, long ago.” The woman then
disappeared, and the princess fell into a short slumber, but from
which she was roused by the old queen, who stood by her bed, and
inquired whether the web were ready. The princess told her that it
was, and handed to her the beautiful piece of weaving. The queen
must now appear content for the second time; but the princess
could easily see that she was not so from good-will.
The king’s daughter now flattered herself that she should be put
to no further trial; but the queen was of a different opinion; for she
shortly after sent the web down to the maiden-bower with the
message, that the princess should make it into shirts for the prince.
The shirts were to be ready before sunrise, otherwise the damsel
must never hope to have the young prince for a husband.
When the princess was alone, she felt sad at heart; for she knew
that she could not sew the queen’s web, and yet could not think of
losing the king’s son, to whom she was so dear. She therefore
wandered about the chamber, and shed a flood of tears. At this
moment, the door was softly, softly opened, and in stepped a very
little woman of most extraordinary appearance and still more
extraordinary manners. The little woman had an enormously large
thumb, so that every one who saw it must be wonderstruck. She
also greeted the princess with: “Peace be with you,” and likewise
received for answer: “Peace with you.” She then asked the young
damsel why she was so sad and lonely. “I may well be sad,”
answered the princess. “The queen has commanded me to make
this web into shirts for the king’s son; and if I have not finished
them to-morrow before sunrise, I shall lose my beloved prince, who
holds me so dear.” The woman then said: “Be of good cheer, fair
maiden; if it is nothing more, I can help you. But then you must
agree to a condition, which I will mention.” At these words the
princess was overjoyed, and asked the little woman what it was she
wished. “I am,” answered she, “called Mother Bigthumb, and I desire
no other reward than that I may be present at your wedding. I have
not been at a wedding since the queen your mother-in-law stood as
bride.” The princess willingly assented to this condition, and the little
woman departed. But the princess lay down to sleep, and slept so
soundly that she did not dream even once of her dear prince.
Early in the morning, before the sun had risen, the door was
opened, and the little woman entered. She approached the bed,
awakened the princess, and gave her some shirts that were sewed
and stitched so curiously that their like was never seen. The old
woman said: “See! so beautifully as this I have not sewn since I
sewed for the queen, when she was about to stand as bride. But
that was long, long ago.” With these words the little woman
disappeared; for the queen was then at the door, being just come to
inquire whether the shirts were ready. The king’s daughter said that
they were, and handed her the beautiful work. At the sight of them
the queen was so enraged that her eyes flashed with fury. She said:
“Well! take him then. I could never have imagined that thou wast so
clever as thou art.” She then went her way, slamming the door after
her.
The king’s son and the king’s daughter were now
to be united, as the queen had promised, and great
preparations were made for the wedding. But the
joy of the princess was not without alloy, when she
thought of the singular guests that were to be
present. When some time had elapsed, and the
wedding was being celebrated in the good old
fashion, yet not one of the little old women
appeared; although the bride looked about in every
direction. At length, when it was growing late, and
the guests were going to table, the princess
discerned the three little women, as they sat in a
corner of the dining hall, at a table by themselves. At the same
moment the king stepped up to them, and inquired who they were,
as he had never seen them before. The eldest of the three
answered: “I am called Mother Bigfoot, and have such large feet
because I have been obliged to sit spinning so much in my time.”
“Oho!” said the king, “if such be the consequence, my son’s wife
shall never spin another thread.” Then turning to the second little
woman, he inquired the cause of her uncommon appearance. The
old woman answered: “I am called Mother Bigback, and am so
broad behind because I have been obliged to sit weaving so much in
my time.” “Oho!” said the king, “then my son’s wife shall weave no
more.” Lastly, turning to the third old woman, he asked her name;
when Mother Bigthumb, rising from her seat, told him that she had
got so large a thumb because she had sewed so much in her time.
“Oho!” said the king, “then my son’s wife shall never sew another
stitch.” Thus the fair princess obtained the king’s son, and also
escaped from spinning, and weaving, and sewing for all the rest of
her life.
When the wedding was over, the three little women went their way,
and no one knew whither they went, nor whence they came. The
prince lived happy and content with his consort, and all passed on
smoothly and peaceably; only the princess was not so industrious as
her strict mother-in-law.

The fairies are always glad when people do not find out who it is
that has benefited them,—for of course Mother Bigfoot, Mother
Bigback, and Mother Bigthumb were really fairies in disguise,—and
were therefore pleased at the end of the Norwegian fairy’s tale.
“Now,” said Titania, and of course her word was law, “I think I
should like a song. Nymphidia, sing to us.” Nymphidia at once stood
up on the stool and all the Queen’s maids of honour stood around it
as they sang
The Queen’s Song

Round about, round about, in a fine ring-a:


Thus we dance, thus we dance, and thus we sing-a:
Trip and go, to and fro, over this green-a,
All about, in and out, for our brave queen-a.

Round about, round about, in a fine ring-a:


Thus we dance, thus we dance, and thus we sing-a:
Trip and go, to and fro, over this green-a,
All about, in and out, for our brave queen-a.

We have danc’d round about in a fine ring-a:


We have danced lustily, and thus we sing-a,
All about, in and out, over this green-a,
To and fro, trip and go, to our brave queen-a.
Nymphidia and all the maids of honour having sung this little song
to their queen, Oberon thought it was time that Bottom should be
made to tell a tale, and he, you may be sure, made a clumsy enough
figure as he took his seat on the tale-teller’s stool, scratched his
head and said, “he didn’t know any fairy tales.” He tried to get away
but could not rise until the King would let him; then when he did not
begin quickly enough, Titania whispered to her maids of honour, and
Hop, Mop and Drop, Pip, Drip and Skip, Tub, Tib and Tick, Pink, Pin
and Quick, Gill, Om and Tit, Wap, Win and Mit all danced about poor
Bottom, pinching and pulling and teasing him until he roared again
and the whole fairy kingdom rang with peals of laughter. “Tell ’em
about Billy MacDaniel,” called out Flute, and without any preface
Bottom at once began telling the story of
The Three Sneezes
Billy MacDaniel was once as likely a young man as ever shook his
brogue at a patron, emptied a quart, or handled a shillelagh; fearing
for nothing but the want of drink; caring for nothing but who should
pay for it; and thinking of nothing but how to make fun over it:
drunk or sober, a word or a blow was ever the way with Billy
MacDaniel; and a mighty easy way it is of either getting into or of
ending a dispute. More is the pity that, through the means of his
thinking, and fearing, and caring for nothing, this same Billy
MacDaniel fell into bad company; for surely the good people are the
worst of all company any one could come across.
It so happened that Billy was going home one clear frosty night
not long after Christmas; the moon was round and bright; but
although it was as fine a night as heart could wish for, he felt
pinched with the cold. “By my word,” chattered Billy, “a drop of good
liquor would be no bad thing to keep a man’s soul from freezing in
him; and I wish I had a full measure of the best.”
“Never wish it twice, Billy,” said a little man in a three-cornered
hat, bound all about with gold lace and with great silver buckles in
his shoes, so big that it was a wonder how he could carry them, and
he held out a glass as big as himself, filled with as good liquor as
ever eye looked on or lip tasted.
“Success, my little fellow,” said Billy MacDaniel, nothing daunted,
though well he knew the little man to belong to the good people;
“here’s your health, any way, and thank you kindly; no matter who
pays for the drink”; and he took the glass and drained it to the very
bottom without ever taking a second breath to it.
“Success,” said the little man; “and you’re heartily welcome, Billy;
but don’t think to cheat me as you have done others,—out with your
purse and pay me like a gentleman.”
“Is it I pay you?” said Billy; “could I not just take you up and put
you in my pocket as easily as a blackberry.”
“Billy MacDaniel,” said the little man, getting very angry, “you shall
be my servant for seven years and a day, and that is the way I will
be paid; so make ready to follow me.”
When Billy heard this he began to be very sorry for having used
such bold words towards the little man; and he felt himself, yet
could not tell how, obliged to follow the little man the livelong night
about the country, up and down, and over hedge and ditch, and
through bog and brake without any rest.
When morning began to dawn, the little man turned round to him
and said, “You may now go home, Billy, but on your peril don’t fail to
meet me in the Fort-field to-night; or if you do it may be the worse
for you in the long-run. If I find you a good servant you will find me
an indulgent master.”
Home went Billy MacDaniel; and though he was tired and weary
enough, never a wink of sleep could he get for thinking of the little
man; but he was afraid not to do his bidding, so up he got in the
evening, and away he went to the Fort-field. He was not long there
before the little man came towards him and said, “Billy, I want to go
a long journey to-night; so saddle one of my horses, and you may
saddle another for yourself, as you are to go along with me, and
may be tired after your walk last night.”
Billy thought this very considerate of his master, and thanked him
accordingly: “But,” said he, “if I may be so bold, sir, I would ask
which is the way to your stable, for never a thing do I see but the
fort here, and the old thorn tree in the corner of the field, and the
stream running at the bottom of the hill, with the bit of bog over
against us.”
“Ask no questions, Billy,” said the little man, “but go over to that
bit of bog, and bring me two of the strongest rushes you can find.”
Billy did accordingly, wondering what the little man would be at;
and he picked out two or three of the stoutest rushes he could find,
with a little bunch of brown blossom stuck at the side of each, and
brought them back to his master.
“Get up, Billy,” said the little man, taking one of the rushes from
him and striding across it.
“Where shall I get up, please your honour?” said Billy.
“Why, upon horseback, like me, to be sure,” said the little man.
“Is it after making a fool of me you’d be,” said Billy, “bidding me
get a horseback upon that bit of a rush? Maybe you want to
persuade me that the rush I pulled but while ago out of the bog over
there is a horse?”
“Up! Up! and no words,” said the little man, looking very angry;
“the best horse you ever rode was but a fool to it.” So Billy, thinking
all this was in joke, and fearing to vex his master, straddled across
the rush. “Borram! Borram! Borram!” cried the little man three times
(which, in English, means to become great), and Billy did the same
after him: presently the rushes swelled up into fine horses, and
away they went full speed; but Billy, who had put the rush between
his legs, without much minding how he did it, found himself sitting
on horseback the wrong way, which was rather awkward, with his
face to the horse’s tail; and so quickly had his steed started off with
him that he had no power to turn round, and there was therefore
nothing for it but to hold on by the tail.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like