100% found this document useful (1 vote)
16 views

Programming with C 20 Concepts Coroutines Ranges and more Updated 2024 2nd Edition Andreas Fertig 2024 Scribd Download

Andreas

Uploaded by

lousmhoni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
16 views

Programming with C 20 Concepts Coroutines Ranges and more Updated 2024 2nd Edition Andreas Fertig 2024 Scribd Download

Andreas

Uploaded by

lousmhoni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Download Full ebookname - Read Now at ebookname.

com

Programming with C 20 Concepts Coroutines Ranges


and more Updated 2024 2nd Edition Andreas Fertig

https://ebookname.com/product/programming-
with-c-20-concepts-coroutines-ranges-and-more-
updated-2024-2nd-edition-andreas-fertig/

OR CLICK BUTTON

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Navigating Communication with Seriously Ill Patients 2e


Apr 25 2024 2nd Edition Elise C. Carey

https://ebookname.com/product/navigating-communication-with-seriously-
ill-patients-2e-apr-25-2024-2nd-edition-elise-c-carey/

ebookname.com

Programming With C 3rd Edition Ravichandran

https://ebookname.com/product/programming-with-c-3rd-edition-
ravichandran/

ebookname.com

With Fabric and Thread More Than 20 Inspired Quilting and


Sewing Patterns 1st Edition Joanna Figueroa

https://ebookname.com/product/with-fabric-and-thread-more-
than-20-inspired-quilting-and-sewing-patterns-1st-edition-joanna-
figueroa/
ebookname.com

Encyclopedia of Clothing and Fashion 1st Edition Valerie


Steele

https://ebookname.com/product/encyclopedia-of-clothing-and-
fashion-1st-edition-valerie-steele/

ebookname.com
Robert Lax 1. ed. Edition Paul J. Spaeth

https://ebookname.com/product/robert-lax-1-ed-edition-paul-j-spaeth/

ebookname.com

Bridging Cultural Conflicts A New Approach for a Changing


World Michelle Lebaron

https://ebookname.com/product/bridging-cultural-conflicts-a-new-
approach-for-a-changing-world-michelle-lebaron/

ebookname.com

The Library of the Abbey of La Trappe A Study of its


History from the Twelfth Century to the French Revolution
with an Annotated Edition of the 1752 Catalogue David N.
Bell
https://ebookname.com/product/the-library-of-the-abbey-of-la-trappe-a-
study-of-its-history-from-the-twelfth-century-to-the-french-
revolution-with-an-annotated-edition-of-the-1752-catalogue-david-n-
bell/
ebookname.com

Data Modeling and Database Design 2nd Edition Narayan S.


Umanath

https://ebookname.com/product/data-modeling-and-database-design-2nd-
edition-narayan-s-umanath/

ebookname.com

Myths Lies and Oil Wars Engdahl

https://ebookname.com/product/myths-lies-and-oil-wars-engdahl/

ebookname.com
Joy s LIFE Diet Four Steps to Thin Forever 1st Edition Joy
Bauer

https://ebookname.com/product/joy-s-life-diet-four-steps-to-thin-
forever-1st-edition-joy-bauer/

ebookname.com
Programming
with C++20
Concepts, Coroutines,
Ranges, and more

Andreas Fertig
Andreas Fertig

Programming with C++20

Concepts, Coroutines, Ranges, and more

2. Edition
© 2024 Andreas Fertig
https://AndreasFertig.com
All rights reserved

Bibliographic information published by the Deutsche Nationalbibliothek


The Deutsche Nationalbibliothek lists this publication in the Deutsche Nationalbibliografie; detailed bib-
liographic data are available on the Internet at http://dnb.dnb.de.

The work including all its parts is protected by copyright. Any use outside the limits of the copyright law
requires the prior consent of the author. This applies in particular to copying, editing, translating and
saving and processing in electronic systems.

The reproduction of common names, trade names, trade names, etc. in this work does not justify
the assumption that such names are to be regarded as free within the meaning of the trademark
and trademark protection legislation and therefore may be used by everyone, even without special
identification.

Planning and text:


Andreas Fertig

Cover art and illustrations:


Franziska Panter
https://franziskapanter.com

Published by:
Fertig Publications
https://andreasfertig.com

ISBN: 978-3-949323-05-8

This book is available as ebook at https://leanpub.com/programming-with-cpp20


Thank you, Brigitte & Karl! You opened the world for me. You were
always there, supporting me, letting me find my own way, making me what
I am.

To Franziska, without her, I would not have accomplished this project.


Never tired of reminding me of my talents, driving me when I’m tired, keep-
ing my focus on. A lot of more could be written here. I like to close with:
Thank You!
4
Using Code Examples

This book exists to assist you during your daily job life or hobbies. All examples in
this book are released under the MIT license.
The main reason for choosing the MIT license was to avoid uncertainty. It is a
well-established open-source license and comes with few restrictions. That should
make it easy to use it even in closed-source projects. If you need a dedicated license
or have questions about the existing licensing, feel free to contact me.

Code download

The source code for this book’s examples is available at


https://github.com/andreasfertig/programming-with-cpp20 .

Used Compilers

For those of you who would like to try out the code with the same compilers and
revisions I used, here you go:

■ GCC 13.2.0

■ Clang 17.0.0
6
About the Author

Andreas Fertig, CEO of Unique Code GmbH, is an experienced trainer and lecturer
for C++ for standards 11 to 23.

Andreas is involved in the C++ standardization committee, developing the


new standards. At international conferences, he presents how code can be written
better. He publishes specialist articles, e.g., for iX magazine, and has published
several textbooks on C++.

With C++ Insights (cppinsights.io), Andreas has created an internationally rec-


ognized tool that enables users to look behind the scenes of C++ and thus to
understand constructs even better.

Before training and consulting, he worked for Philips Medizin Systeme GmbH for
ten years as a C++ software developer and architect focusing on embedded systems.

You can find him online at andreasfertig.com.


8
About the Book

Programming with C++20 teaches programmers with C++ experience the new fea-
tures of C++20 and how to apply them. It does so by assuming C++11 knowledge.
Elements of the standards between C++11 and C++20 will be briefly introduced, if
necessary. However, the focus is on teaching the features of C++20.
You will start with learning about the so-called big four Concepts, Coroutines,
std::ranges, and modules. The big four a followed by smaller yet not less important
features. You will learn about std::format, the new way to format a string in C++.
In chapter 6, you will learn about a new operator, the so-called spaceship operator,
which makes you write less code.
You then will look at various improvements of the language, ensuring more con-
sistency and reducing surprises. You will learn how lambdas improved in C++20 and
what new elements you can now pass as non-type template parameters. Your next
stop is the improvements to the STL.
Of course, you will not end this book without learning about what happened in
the constexpr-world.

Style and conventions

The following shows the execution of a program. I used the Linux way here and
skipped supplying the desired output name, resulting in a.out as the program name.

$ ./a.out
Output

Hello, Programming with C++20!


10

■ <string> stands for a header file named string.

■ [[xyz]] marks a C++ attribute with the name xyz.

From time to time, I use an element from a previous standard after C++11. I ex-
plain these elements in dedicated standard boxes such as the following:

0.1 C++14: A sample element

A sample element from C++14.

These boxes carry the standard in which this element was introduced and are num-
bered such that I can reference them like this: Std-Box 0.1.
All listings are numbered and sometimes come with annotations which I refer to
like this A .
References carry a page number in case the reference isn’t on the same page. For
example, Std-Box 0.1 has no page number because it appears on the same page.

Feedback

This book is published on Leanpub (https://leanpub.com/programming-with-


cpp20) as a digital version. A full-color and a grayscale paperback version are
available on Amazon. It helps if you indicate the book type you’re referring to.

In any case, I appreciate your feedback. Please report it to me, whether it be a


typo, a grammatical error, an issue with naming variables or functions, or another
logical concern. You can send your feedback to [email protected].

PDF/Paperback vs. epub

As with most of my material, the book is written in LATEX. The epub version is
generated by a custom script which first translates LATEX into Markdown and then
translates Markdown into epub with the help of pandoc. This comes with some
limitations. Currently, the bibliography does not use the same style as the PDF, and
About the Book 11

the index is missing in the epub.

Another issue I have with the epub is that I do not own a reader device my-
self. I tested it with Apple’s Books.However, please tell me if you have better
knowledge of optimizing the output.

Thank you

I like to say thank you to everyone who reviewed drafts for this book and gave me
valuable feedback. Thank you! All this feedback helped to improve the book. Here
is a list of people who provided feedback: Vladimir Krivopalov, Hristiyan Nevelinov,
John Plaice, Peter Sommerlad, Salim Pamukcu, Jonathan Di Cosmo, and others.
A special thanks goes to Fran Buontempo, editor of ACCU’s Overload magazine.
She provided extensive feedback from the beginning and was never tired of pointing
out some grammar issues along with poking to the base of my code examples, helping
me make them better.

Revision History

2021-01-30: First release (Leanpub)


2021-04-22: Various spelling and grammar updates due to feedback. Added chapter
9. (Leanpub)
2021-10-01: Added chapter 3. (Leanpub)
2021-10-15: Added chapter 10. (Leanpub)
2021-10-18: Various spelling and grammar updates due to feedback. Fixed listing
numbers. Better styling of boxes (Leanpub)
2021-10-25: Added chapter 4. Various layout improvements. (Leanpub)
2021-10-27: Added chapter 11. Various layout improvements. (Leanpub)
2021-11-10: Added chapter 12, rewrote chapter 1. Various layout improvements.
(Leanpub)
2021-11-26: Full release (Leanpub, Amazon)
2023-01-03: Various spelling and grammar updates due to feedback. (Leanpub)
12

2024-02-06: Prepareing second edition. (Leanpub, Print)


Table of Contents

1 Concepts: Predicates for strongly typed generic code 17


1.1 Programming before Concepts . . . . . . . . . . . . . . . . . . . 18
1.2 Start using Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.3 Application areas for Concepts . . . . . . . . . . . . . . . . . . . 22
1.4 The requires-expression: The runway for Concepts . . . . . . 23
1.5 Requirement kinds in a requires-expression . . . . . . . . . . . 25
1.6 Ad hoc constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.7 Defining a concept . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.8 Testing requirements . . . . . . . . . . . . . . . . . . . . . . . . . . 32
1.9 Abbreviated function template with auto as a generic pa-
rameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
1.10 Using a constexpr function in a concept . . . . . . . . . . . . . 36
1.11 Concepts and constrained auto types . . . . . . . . . . . . . . . 38
1.12 The power of Concepts: requires instead of enable_if . . . 40
1.13 Concepts ordering . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
1.14 Improved error message . . . . . . . . . . . . . . . . . . . . . . . 56
1.15 Existing Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

2 Coroutines: Suspending functions 65


2.1 Regular functions and their control flow . . . . . . . . . . . . . 65
2.2 What are Coroutines . . . . . . . . . . . . . . . . . . . . . . . . . . 67
2.3 The Elements of Coroutines in C++ . . . . . . . . . . . . . . . . 69
2.4 Writing a byte-stream parser the old way . . . . . . . . . . . . 78
2.5 A byte-stream parser with Coroutines . . . . . . . . . . . . . . 81
2.6 A different strategy of the Parse generator . . . . . . . . . . . 91
14

2.7 Using a coroutine with custom new / delete . . . . . . . . . . . 98


2.8 Using a coroutine with a custom allocator . . . . . . . . . . . . 100
2.9 Exceptions in coroutines . . . . . . . . . . . . . . . . . . . . . . . 102

3 Ranges: The next-generation STL 107


3.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
3.2 The who is who of ranges . . . . . . . . . . . . . . . . . . . . . . . 114
3.3 A range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
3.4 A range algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
3.5 A view into a range . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
3.6 A range adaptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
3.7 The new ranges namespaces . . . . . . . . . . . . . . . . . . . . . 121
3.8 Ranges Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
3.9 Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
3.10 Creating a custom range . . . . . . . . . . . . . . . . . . . . . . . 125

4 Modules: The superior way of includes 131


4.1 Background about the need for modules . . . . . . . . . . . . 131
4.2 Creating modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
4.3 Applying modules to an existing code base . . . . . . . . . . . 136

5 std::format: Modern & type-safe text formatting 145


5.1 Formatting a string before C++20 . . . . . . . . . . . . . . . . . 145
5.2 Formatting a string using std::format . . . . . . . . . . . . . . 153
5.3 Formatting a custom type . . . . . . . . . . . . . . . . . . . . . . 158
5.4 Referring to a format argument . . . . . . . . . . . . . . . . . . . 164
5.5 Using a custom buffer . . . . . . . . . . . . . . . . . . . . . . . . . 165
5.6 Writing our own logging function . . . . . . . . . . . . . . . . . 168

6 Three-way comparisons: Simplify your comparisons 175


6.1 Writing a class with equal comparison . . . . . . . . . . . . . . 176
6.2 Writing a class with ordering comparison, pre C++20 . . . . 180
6.3 Writing a class with ordering comparison in C++20 . . . . . 183
6.4 The different comparison categories . . . . . . . . . . . . . . . 186
6.5 Converting between comparison categories . . . . . . . . . . 190
6.6 New operator abilities: reverse and rewrite . . . . . . . . . . . 192
6.7 The power of the default spaceship . . . . . . . . . . . . . . . . 193
About the Book 15

6.8 Applying a custom sort order . . . . . . . . . . . . . . . . . . . . 196


6.9 Spaceship-operation interaction with existing code . . . . . 197

7 Lambdas in C++20: New features 201


7.1 [=, this] as a lambda capture . . . . . . . . . . . . . . . . . . . . . 201
7.2 Default-constructible lambdas . . . . . . . . . . . . . . . . . . . 205
7.3 Captureless lambdas in unevaluated contexts . . . . . . . . . 207
7.4 Lambdas in generic code . . . . . . . . . . . . . . . . . . . . . . . 209
7.5 Pack expansions in lambda init-captures . . . . . . . . . . . . . 214
7.6 Restricting lambdas with Concepts . . . . . . . . . . . . . . . . 217

8 Aggregates: Designated initializers and more 223


8.1 What is an aggregate . . . . . . . . . . . . . . . . . . . . . . . . . . 223
8.2 Designated initializers . . . . . . . . . . . . . . . . . . . . . . . . . 224
8.3 Direct-initialization for aggregates . . . . . . . . . . . . . . . . . 235
8.4 Class Template Argument Deduction for aggregates . . . . . 241

9 Class-types as non-type template parameters 247


9.1 What are non-type template parameters again . . . . . . . . 247
9.2 The requirements for class types as non-type template pa-
rameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
9.3 Class types as non-type template parameters . . . . . . . . . 250
9.4 Building a format function with specifier count check . . . . 253

10 New STL elements 265


10.1 bit_cast: Reinterpreting your objects . . . . . . . . . . . . . . 265
10.2 endian: Endianness detection at compile time . . . . . . . . . 268
10.3 to_array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
10.4 span: A view of continuous memory . . . . . . . . . . . . . . . . 272
10.5 source_location: The modern way for __FUNCTION__ . . . . . 275
10.6 contains for all associative containers . . . . . . . . . . . . . . 282
10.7 starts_with and ends_with for std::string . . . . . . . . . . . 284

11 Language Updates 287


11.1 Range-based for-loops with initializers . . . . . . . . . . . . . . 287
11.2 New Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
11.3 using enums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
16

11.4 conditional explicit . . . . . . . . . . . . . . . . . . . . . . . . . . 296

12 Doing (more) things at compile-time 301


12.1 The two worlds: compile- vs. run-time . . . . . . . . . . . . . . 301
12.2 is_constant_evaluated: Is this a constexpr-context? . . . . . 305
12.3 Less restrictive constexpr-function requirements . . . . . . . 309
12.4 Utilizing the new compile-time world: Sketching a car rac-
ing game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
12.5 consteval: Do things guaranteed at compile-time . . . . . . 315
12.6 constinit: Initialize a non-const object at compile-time . . 321

Acronyms 327

Bibliography 329

Index 331
Chapter 1

Concepts:
Predicates for strongly typed
generic code

Templates have been with C++ since the early beginnings. Recent standard updates
have added new facilities, such as variadic templates. Templates enable Generic Pro-
gramming (GP), the idea of abstracting concrete algorithms to get generic algorithms.
They can then be combined and used with different types to produce a wide variety
of software without providing a dedicated algorithm for each type. GP or Template
Meta-Programming (TMP) are powerful tools. For example, the Standard Template
Library (STL) heavily uses them.
However, template code has always been a bit, well, clumsy. When we write a
generic function, we only need to write the function once; then it can be applied to
various different types. Sadly, when using the template with an unsupported type,
finding any error requires a good understanding of the compiler’s error message.
All we needed to face such a compiler error message was a missing operator< that
wasn’t defined for the type. The issue was that we had no way of specifying the re-
quirements to prevent the misuse, and at the same time, give a clear error message.
18

Concepts vs concepts vs concepts

This chapter comes with an additional challenge. The language feature we will discuss in this
chapter is called Concepts. We can also define a concept ourselves, and there is a concept key-
word. When I refer to the feature itself, it is spelled with a capital C, Concepts. The lowercase
version is used when I refer to a single concept definition, and the code-font version concept
refers to the keyword.

1.1 Programming before Concepts

Let’s consider a simple generic Add function. This function should be able to add an
arbitrary number of values passed to it and return the result. Much like this:
1 const int x = Add(2,3,4,5);
2 const int y = Add(2,3);
3 const int z = Add(2, 3.0); A This should not compile

While the first two calls to Add, x and y, are fine, the third call should result in a
compile error. With A we are looking at implicit conversions, namely a promotion
from int to double because of 3.0. Implicit conversions can be a good thing, but in
this case, I prefer explicitness over the risk of loss of precision. Here Add should only
accept an arbitrary number of values of the same data type.
To make the implementation a little more challenging, let’s say that we don’t want
a static_assert in Add, which checks that all parameters are of the same type. We
would like to have the option of providing an overload to Add that could handle cer-
tain cases of integer promotions.
We start with an implementation in C++1 to see the power of Concepts. For
the implementation of Add, we obviously need a variadic function template as well
as a couple of helpers. The implementation I present here requires two helpers,
are_same_v and first_arg_t. You can see the implementation in Listing 1.1.

1 template<typename T, typename... Ts>


2 constexpr inline bool are_same_v =
Listing 1.1

3 std::conjunction_v<std::is_same<T, Ts>...>;
4

5 template<typename T, typename...>
Chapter 1: Concepts: Predicates for strongly typed generic code 19

6 struct first_arg {
7 using type = T;

Listing 1.1
8 };
9

10 template<typename... Args>
11 using first_arg_t = typename first_arg<Args...>::type;

The job of are_same_v, which is a C++14 variable template ( Std-Box 1.1), is to


ensure, with the help of the type-traits std::is_same and std::conjunction_v,
that all types in the parameter pack passed to are_same_v are the same. For that, the
variable template uses the usual trick of splitting up the first argument from the pack
and comparing all other arguments against this first one.

1.1 C++14: Variable templates

Variable templates were introduced with C++14. They allow us to define a variable, which is a
template. This feature allows us to have generic constants like π :

Listing 1.2
1 template<typename T>
2 constexpr T pi(3.14);

One other use case is to make TMP more readable. Whenever we had a type-trait with a value
we wanted to access, before C++14, we needed to do this: std::is_same<T, int>::value
. Admittingly, the ::value part was not very appealing. Variable templates allow the value of
::value to be stored in a variable.
Listing 1.3

1 template<typename T, typename U>


2 constexpr bool is_same_v = std::is_same<T, U>::value;

With that, the shorter and more readable version is is_same_v<T, int>. Whenever you see a
_v together with a type-trait, you’re looking at a variable template.

Our second helper, first_arg_t, uses a similar trick. It extracts the first type
from a pack and stores it in a using-alias. That way, we have access to the first data
type in a parameter pack, and since we later ensure that all types in the pack are the
same, this first type is as good as that from any other index choice in the parameter
pack.
20

Great, now that we have our helpers in place, let’s implement Add. Listing 1.4
provides an implementation using C++17.

1 template<typename... Args>
2 std::enable_if_t<are_same_v<Args...>, first_arg_t<Args...>>

Listing 1.4
3 Add(const Args&... args) noexcept
4 {
5 return (... + args);
6 }

In this implementation, as promised, Add is a variadic function template, which


we quickly spot looking at the template head. If we go down two lines, we can see
the function’s name, Add, and that it takes the parameter pack as a const &.
The body of Add reveals that I use C++17’s fold expressions ( Std-Box 1.2) to apply
the plus operation to all the parameter packs elements.

1.2 C++17: Fold expressions

Before C++17, whenever we had a parameter pack, we needed to recursively call the function
that received the pack and split up the first parameter. That way, we could traverse a parameter
pack. C++17 allows us to apply an operation to all elements in the pack. For example, int
result = (... + args); applies the + operation to all elements in the pack. Assuming that
the pack consists of three objects, this example will produce int result = arg0 + arg1 +
arg2;. This is much shorter to write than the recursive version. That one needs to be terminated
at some point. With fold expressions, this is done automatically by the compiler. We can use other
operations instead of +, like −, /, ∗, and so on.
The important thing to realize about fold expressions is that it is only a fold expression if the pack
expansion has parentheses around it and an operator like +.

So far, I hope that’s all understandable. The part I heavily object to, despite the
fact that it is my own code, is the line with the enable_if_t. Yes, it is the state-of-
the-art enable_if because, with the _t, we don’t need to say typename in front of
it. However, this single line is very hard to read and understand. Depending on your
knowledge of C++, it can be easy, but remember the days when you started with C++.
There is a lot that one has to learn to understand this single line.
The first part, or argument, is the condition. Here, we pass are_same_v. Should
this condition be true, the next parameter which is first_arg_t, gets enabled. This
then becomes the return type of Add. Right, did you also miss the return type initially?
Chapter 1: Concepts: Predicates for strongly typed generic code 21

Should the condition be false, then this entire expression isn’t instantiable. We speak
of substitution failure is not an error (SFINAE) as the technique used here, and this
version of Add isn’t used for lookups by the compilers. The result is that we can end
up with page-long error messages where the compiler informs us about each and
every overload of Add it tried.
One more subtle thing is that, in this case, enable_if does something slightly
different than just enabling or disabling things. It tells us the requirements for this
function. Yet, the name enable_if doesn’t give many clues about that.
All these things are reasons why people might find templates tremendously diffi-
cult to process. But, yes, I know, those who stayed accommodated to all these short-
comings.
Now it is time to see how things change with C++20.

1.2 Start using Concepts

Sticking with the initial example, we ignore the helpers, as they stay the same. List-
ing 1.5 presents the C++20 implementation of Add.

1 template<typename... Args>
2 A Requires-clause using are_same_v to ensure all Args are of the same
type.

Listing 1.5
3 requires are_same_v<Args...>
4 auto Add(Args&&... args) noexcept
5 {
6 return (... + args);
7 }

Here, we can see that Add remains a variadic function template, probably not the
biggest surprise. Let’s skip two lines again and go to the definition of Add. What first
springs into our eyes is the return type. I chose auto. But the important thing is that
the return type is there! The rest of the function’s signature, as well as the function
body, are unchanged. I see this return type as the first win. Before, the enable_if
obfuscated the return type.
The biggest improvement is the line that says requires. Isn’t that what’s really
going on here? This function Add requires that are_same_v is true. That’s all. I find
22

that pretty easy to read. The intent is clearly expressed without obfuscating anything
or requiring weird tricks. Okay, maybe we must look up what are_same_v does, but
I can live with that.
We are looking at one of the building blocks of Concepts in Listing 1.5 on page 21,
the requires-clause.

1.3 Application areas for Concepts

Before discussing how we can create Concepts, let’s first see where we can apply
them. Figure 1.1 on page 23 lists all the places in a template declaration where we
can apply Concepts.
We see a type-constraint in C1. In this place, we can only use Concepts. We can use
a type-constraint instead of either class or typename in a template-head to state as
early as possible that this template takes a type deduced by the compiler, but it must
meet some requirements.
The next option is with C2, using a requires-clause. We already applied that in our
Add example in Listing 1.5 on page 21. In a requires-clause, we can use either con-
cepts or type-traits. The expression following the requires must return a boolean
value at compile time. If that value is true, the requirement(s) is (are) fulfilled.
The two places of C3 and C4 are similar. They both apply to placeholder types
constraining them. We can also use Concepts to constrain auto variables, which we
will see later. A constraint placeholder type works only with Concepts. Type-traits
are not allowed. In C4, we see something that you might already know from C++14’s
generic lambdas, Std-Box 7.1 on page 210, auto as a parameter type. Since C++20,
they are no longer limited to generic lambdas.
At the end, we have the trailing requires-clause. This one is similar to the requires-
clause. We can use Concepts or type-traits and can use boolean logic to combine
them. Table 1.1 on page 23 gives guidance on when to use which constraint form.
Chapter 1: Concepts: Predicates for strongly typed generic code 23

type-constraint

requires-clause
template<C1 T>
requires C2<T>
C3 auto Fun(C4 auto param) requires C5<T>

trailing requires-clause
constrained placeholder type

Figure 1.1: The different places where we can constrain a template or template argument.

Table 1.1: When to use which constraint form

Type When to use

C1 type-constraint Use this when you already know that a template type
parameter has a certain constraint. For example, not all
types are allowed. In Figure 1.1 the type is limited to a
floating-point type.

C2 requires-clause Use this when you need to add constraints for multiple
template type or non-type template parameters.

C5 trailing requires-clause Use this for a method in a class template to constrain it


based on the class template parameters.

1.4 The requires-expression: The runway for Concepts

We’ve already seen the two forms of a requires-clause. It is time to look at our Add
example again and see what we can improve with the help of Concepts.
The current implementation of Add only prevents mixed types. Let’s call this re-
quirement A of Add. By that, the implementation leaves a lot unspecified:

B Add can nonsensically be called with only one parameter. The function’s name,
on the other hand, implies that things are added together. It would make more
sense if Add would also require to be called with at least two parameters. Ev-
erything else is a performance waste.
C The type used in Args must support the + operation. This is a very subtle re-
quirement that harshly yells at us once we violate it. It is also a design choice of
24

Parameter list of the


requires-expression.

requires(T t, U u)
{ Body of the
// some requirements
requires-expression
}

One or multiple requirements.

Figure 1.2: Parts of a requires-expression.

the implementor of Add. Instead of operator+, one could also require that the
type comes with a member function Addition. That would, of course, rule out
built-in types. Should we miss that, we again get these page-long errors that
are hard to see through. Only documentation helps at this point, and documen-
tation over time may disagree with the implementation. In such a case, I prefer
a check by the compiler over documentation.

D The operation + should be noexcept, since Add itself is noexcept. Did you
spot that initially? The implementation of Add in Listing 1.5 on page 21 and
before was always marked noexcept. Why? Because it mainly adds num-
bers, and I don’t want to have a try-catch-block around something like 3 + 4.
But since Add is a generic function, it also works with, for example, a std::
string, which can throw an exception. Writing a check for the noexceptness
of operator+ pre C++17 is an interesting exercise.

E The return type of operation + should match that of Args. Another interesting
and often overlooked requirement. It is surprising should operator+ of type
T return a type U. Sometimes, there are good reasons for such a behavior, but
it doesn’t seem plausible in the case of Add. Let’s restrict this as well.

Implementing all these requirements above the standard provides us with a


requires-expression. Figure 1.2 shows how a requires-expression looks.
I read it like a constructor of type requires. You can also see it as a function
without a return type. After the name requires, which is always the same, we have
the optional parameter list. Like in a regular function, this parameter list can be
Discovering Diverse Content Through
Random Scribd Documents
the Fo’castle has given them something to sit on, something they
can see the world from, and on its ridgepole they perch, singing at
life in general with a praiseworthy persistence. The bird really has
two songs, one the nuptial aria, the other the domestic tune; it sings
the first in the nest-building, egg-laying season, and the second from
the close of the honeymoon to the silence in the fall. I was amazed
this year at the suddenness of the change. On the afternoon of July
1st I heard the birds on my roof singing aria number one; on the
morning of July 2d they had turned the page to aria number two. The
songs are alike; they resemble each other in musical “shape,” but
the first is much more of a warble than the second.
On throwing open my door on the dunes, the morning sea, and the
vast empty beach with its coast guard paths, I find the house being
stormed by swallows—they are picking up the half-torpid flies that
have spent the night on the shingles and just buzzed off—and on
looking north and south along the dunes I see swallows everywhere.
The grass glistens in the early morning light, the slant of the sun
picks out the ripening spears, the graceful birds swim close above
the green. Most of these birds are bank swallows, Riparia riparia, but
I often see barn swallows, Hirundo erythrogastra, and tree swallows,
Iridoprocne bicolor, scattered in among them. A little after seven
o’clock they melt away. Through the day stray birds come foraging,
but the swarm is a morning affair. The bank swallows (the bird with
whitish underparts and a dark band across the breast) have nests
north of Nauset Station in a clay stratum of the great bank; the tree
swallows and the barn swallows live farther inland near the farms.
Some say that the bank swallows nest in these dunes. I have never
found their nests in this living sand, but the swallows may manage it,
after all. Time and again have I been astounded at the manner in
which animals use this sand as if it were ordinary earth. Not long
ago, on the top of big dune, I found that moles had tunnelled a
surface of live sand for six or seven feet.
Tern Coming to Full Stop Head-
on into the Wind
The common tern, Sterna hirundo, here called the mackerel gull,
dominates both the beach and the summer day. Three or four
thousand of these birds are nesting in the region; there are nests on
the dunes, and whole colonies on certain gravelly areas in the marsh
islands near Orleans. All day long I watch them flying to and fro past
my windows, now sailing with a favouring wind, now battling into an
opposing breeze; I see them going along the breakers long before
sunrise, white birds flying past a rosiness of eastern sky and an
ocean still blue and dark with night; I see them pass like spiritual
creatures in the dusk. There are crowded days when I live in a cloud
of their wings and the clamour of their cries.
Sterna hirundo, the common tern—Wilson’s tern, some call him—
is indeed a lovely bird. His dominant colours are pearl-grey and
white, his wings are bent, he is from thirteen to sixteen inches long,
and he is marked by a black hood, an orange-coral bill tipped with
black, and bright vermilion-orange legs and feet. To my ear, the
bird’s call has a cawing quality; it is, indeed, a cawing screech with
an “e” sound and a high pitch. Harsh though it is, it is not
disagreeable; moreover, it is capable of wide emotional variations.
Going south on a recent day along the dunes, I arrived at the place
where the parent terns, homing from the sea, were crossing the sand
bar on their way to their nests, and as the birds came in sight of their
mates and their fledglings, their cry changed its quality, and took on
a kind of wild, harsh tenderness that was touching to hear.
On Monday morning last, as I sat writing at my west windows, I
heard a tern give a strange cry, and on looking out and up I saw a
bird harrying the female marsh hawk, of whose visits to the dunes I
have already told. The sea bird’s battle cry was entirely new to my
ear. “Ke’ke’ke’aow!” he cried; there was warning in the harsh, horny
cry, danger and anger. The greater bird, flapping her wings as if they
were spreads of paper—the winging of this hawk, near earth, is
sometimes curiously like the winging of a butterfly—made no
answer, but sank to earth slowly, wings outspread, and rested for a
long half minute on the shell-strewn floor of the sand pit forty feet
back from my house. Thus perched motionless, she might have
been a willing mark. Scolding without pause, the tern, who had
followed the enemy down into the pit, then rose and dived on her as
he might have dived on a fish. The hawk continued to sit motionless.
It was an extraordinary scene. Regaining level wing just above the
hawk’s head, the tern instantly climbed and dived again. At his third
dive, the hawk took off, flying ahead and low across the sand pit.
The battle then moved into the dunes, and the last I saw of the affair
was the hawk abandoning the hills and flying south unpursued far
out over the marsh.
Watching the hawk thus a-squat on the sand in a summer intensity
of light, with the grey sea bird angrily assailing her, there came into
my mind a thought of the ancient Egyptian representations of
animals and birds. For this hawk in the pit was the Horus Hawk of
the Egyptians, the same poise, the same dark blood-fierceness, the
same authority. The longer I live here and the more I see of birds
and animals, the greater my admiration becomes for those artists
who worked in Egypt so many long thousand years ago, drawing,
painting, carving in the stifling quiet of the royal tombs, putting here
ducks frightened out of the Nile marshes, here cattle being herded
down a village street, here the great sun vulture, the jackal, and the
snake. To my mind, no representations of animals equal these
Egyptian renderings. I do not write in praise of faithful delineation or
pictorial usage—though the Egyptian drew from his model with care
—but of the unique power to reach, understand, and portray the very
psyche of animals. The power is particularly notable in Egyptian
representations of birds. A hawk of stone carved in hardest granite
on a temple wall will have the soul of all hawks in his eyes.
Moreover, there is nothing human about these Egyptian creatures.
They are self-contained and aloof as becomes folk of a first and
intenser world.
So completely do the thronging terns dominate the beach that they
will often gather to chivvy off a human intruder. I am often chased all
the way to Nauset. Three made for me yesterday afternoon as I was
going north at two o’clock, trudging the hot and heavy sand.
It is an odd, a rather amusing experience to be thus barked at and
chivvied along by birds. Down the beach they followed me, keeping
pace with me and stopping when I stopped, their swallow-like tail
feathers fish-tailing out as they manœuvred close above my head.
About once every half minute one of the three would climb twenty or
thirty feet above me and behind, tread air for a second or two, and
then swoop directly down at me with a scolding cry, the rush ending
in an up-lane scarce a foot above my head. So soundly was I
scolded, and so constant was the sharp clamour, that one might
have thought that the birds had found me pirating eggs and
nestlings. As a matter of fact, I was miles away from any nest or
nesting place. Those who disturb terns actually on their nests are
chivvied by dozens in just such a manner, and are even struck, and
struck vigorously, by the birds.
I suspect the marsh hawk of being on her way to raid these nests.
Madam Hawk has probably been sitting on eggs of her own, for I
have seen little of her since she gave up her daily forays sometime
in the spring.
From mid-June to mid-July, the terns are at their best. Their eggs
are hatching, the fish are running, and all day long the parent birds
are going back and forth between their nests and the sea. When I
open my door at sunrise, the terns are already passing my house,
flying twenty or thirty feet above the curling, oncoming seas. Hour by
hour they pass in two endless streams, one going fishing, the other
bringing home the catch; hour after hour they pass—thousands of
birds an hour when the fishing is good and near at hand. Returning
birds, almost without exception, hold silvery fish crosswise in their
bills, and, unlike the crow in the fable, a tern can cry out without
dropping his prize.
The great majority of these birds are males bringing food to their
mates and the new-born young. The catch usually consists of three-
and four-inch sand eels, but I occasionally see birds flying bow-down
with tinker mackerel. Sometimes a bird passes carrying two “eels,”
holding the pair as best he can.
A week ago, just after two o’clock on a bright afternoon, the birds
suddenly came streaming from everywhere to the surf along the
dunes. Skates had again driven in a people of “eels.” It was high
tide; the seas gathered and broke, the heaviest shaking the beach.
Into the curling baroque crests of the waves, into the advancing
slopes of the gathering green swells, into the race and flow of white
seethe and yellow sand, the bright air rained down birds on the now
doubly imperilled and darting prey. The air was cut with wings and
pierced with eager, hungry, and continuous cries. The birds make
plummet dives and strike up jets of water from the surf. The
harassed fish moving south, the terns followed after them; an hour
later, through field glasses, I could see the thing still going on just
north and seaward of the shoals.
Piratic jaegers, Stercorarius pomarinus, Stercorarius parasiticus,
apparently never trouble these Eastham birds. I have seen but one
jaeger on this beach, and that a solitary bird who chanced to pass
the house one morning last September. Cape Cod neighbours,
however, tell me that jaegers are numerous in the bay, and that they
harry the terns who fish the shoals off Billingsgate.
Almost every day, in the full heat of noontide, I go down to the
lower beach and lie down for a while on the hot sand, an arm over
my eyes. The other day, in a spirit of fun, I raised my arm toward a
passing tern—the returning birds fly scarce thirty feet above the
beach—and to my amusement the creature paused, sank, and
hovered above me for a few seconds scarce ten feet from my hand. I
saw then that its under plumage, instead of being white, was a lovely
faint rose; I had halted a roseate tern, Sterna dougalli. I wriggled my
fingers; the bird responded with a cry in which I read bewildered
indignation; then on it flew, and the incident ended.
This year a number of laughing gulls, Larus atricilla, accompany
the terns fishing, the dozen or so gulls keeping to themselves while
flying with their neighbours.
The most interesting adventure with birds I have had this summer I
had with a flock of least terns, Sterna antillarum. It came to pass that
early one morning in June, as I happened to be passing big dune, a
covey of small terns unexpectedly sailed out at me and hovered
about me, scolding and complaining. To my great delight, I saw that
they were least terns or “tit gulls,” rare creatures on our coast, and
perhaps the prettiest and most graceful of summer’s ocean birds. A
miniature tern, the “leastie,” scarce larger than a swallow, and you
may know him by the lighter grey of his plumage, his bright lemon-
yellow bill, and his delicate orange-yellow feet.
The birds were nesting at the foot of big dune, and I had disturbed
their peace. In the splendour of morning they hung above me, now
uttering a single alarmed cheep, now a series of staccato cries.
The Tern Chick
I walked over to the nests.
The nest of such a beach bird is a singular affair. It is but a
depression, and sometimes scarcely that, in the open, shelterless
beach. “Nest building on the open sand,” says Mr. Forbush, “is but
the work of a moment. The bird alights, crouches slightly, and works
its little feet so rapidly that the motion seems a mere blur, while the
sand flies out in every direction as the creature pivots about. The
tern then settles lower and smooths the cavity by turning and
working and moving its body from side to side.”
I have mislaid the scrap of paper on which I jotted down the
number of nests I found that morning, but I think I counted twenty to
twenty-five. There were eggs in every nest, in some two, in others
three, in one case and one only, four. To describe the coloration of
the shells is difficult, for there was a deal of variation, but perhaps I
can give some idea of their appearance by saying that they were
beach-coloured with overtones of bluish green, and speckled with
browns and violet-browns and lavenders. What interested me most,
however, was not the eggs, but the manner in which the birds had
decorated their nests with pebbles and bits of shell. Here and there
along the beach, the “leasties” had picked up flat bits of sea shell
about the size of a finger nail, and with these bits they had lined the
bowl of their nests, setting the flat pieces in flat, like parts of a
mosaic.
For two weeks I watched these “leasties” and their nests, taking
every precaution not to disturb or alarm the setting birds. Yet I had
but to pass anywhere between them and the tide to put them up, and
when I walked south with coast guardsmen, I heard single cries of
alarm in the starry and enormous night. Toward the end of June, a
sudden northeaster came.
It was a night storm. I built a little fire, wrote a letter or two, and
listened to the howling wind and the bursts of rain. All night long, and
it was a wakeful, noisy night, I had the “leasties” on my mind. I felt
them out there on the wild shelterless beach, with the black gale
screaming over them and the rain pouring down. Opening my door, I
looked for a moment into the drenching blackness and heard a great
roaring of the sea.
The tide and the gale had ebbed together when I rose at five the
next morning, but there was still wind and a grey drizzle. At the foot
of big dune I found desolation. The tide had swept the beach. Not a
nest remained or a sign of a nest, and the birds had gone. Later that
day, just south of big dune, I saw bits of bluish-green eggshell in a
lump of fresh weed. Where the birds went to, I never knew. Probably
to a better place to try again.
Bless me! I thought, returning; what of the song sparrows?
Through the drenching grass, bare-legged, I hurried to the dusty-
miller bush. The sand had been moving during the night; it had crept
along the dunes, it had rained down with the drops of rain, and the
bush was now well embedded. Indeed, it was a bush no more, but a
thicket of separate stalks growing out of a deep, rain-soaked mound
of sand. As I drew close to it, I saw through the rain the prudent eye
of Madam Sparrow aglint in the leaves. The sand had risen to within
an inch of her nest, the leaves which concealed it were awry with
wind and choked with sand, but there sat the little bird, resolved and
dutiful. She raised her brood—how well she deserved to—and some
time in July the whole family moved out into the dunes.
I must now add a paragraph from my autumnal notes and tell of
my last sight of the great summer throng of terns. It was an
unforgettable experience. During August the birds thinned out, and
as the month drew to a close, whole days passed without a sight or
sign of their presence. By September 1st, I imagined that most of
them had gone. Then came the unexpected. On Saturday,
September 3d, friends came down the beach to see me, and at the
close of their visit, as I opened the Fo’castle door, I found that the air
above the dunes was snowy with young terns. The day had been
mild, and the late afternoon light was mild and rosy golden—the sun
was an hour from his setting—and high in space and golden light the
myriads of birds drifted and whirled like leaves. North and south we
saw them for miles along the dunes. For twenty minutes, perhaps, or
half an hour, the swarming filled my sky, and during all that time I did
not hear a single bird utter a single sound.
At the end of that period, withdrawing south and inland, the
gathering melted away.
It was really a very curious thing. Apparently some impulse from
heaven had suddenly seized upon the birds, entered into their
feathered breasts, and led them into the air above the dunes.
Whence came that spirit, whence its will, and how had it breathed its
purpose into those thousand hearts? The whole performance
reminded me very much of a swarming of bees. A migrational
impulse, yes, and something more. The birds were flying high, higher
than I had ever seen terns go, and as far as I could judge—or guess
—the great majority of the fliers were young birds of the year. It was
a rapture, a glory of the young. And this was the last of the terns.
A Cape Cod
Late August, and day by day, I see more shore birds and see them
oftener. All summer long there have been sandpipers and ringnecks
on the beach, but earlier in the season the birds are elusive and may
disappear for days. The first great flocks to return from the Northern
breeding grounds arrived here about the middle of July. I remember
their coming. For four interminable days a strong and tireless
southwest wind had billowed across the lagoon and off to a smoky
sea; on the morning of the fifth day, just before sunrise, this wind had
died; then had come dullness and quiet, and, between nine and ten
o’clock, a breath of easterly air. All that fifth afternoon the beach had
been black with birds, most of them ringnecks or semipalmated
plovers. The long southwester had apparently dammed up a great
migrational stream. These first flocks were vagrant mobs. Walking to
Nauset between two and three o’clock, I must have put up between
two and three thousand birds. As I drew near, mob after mob after
mob crowded the air and sought feeding grounds ahead. The
smaller autumnal flocks had flown in psychic unity, rising and falling,
wheeling and alighting together; these mobs scattered and divided
into wandering companies.
Late August, and my wild ducks, having raised their families, are
returning by hundreds to the marsh. During May and June and early
July, when I wandered about this region in the night, I heard no
sound from the flats. Now, when I get out to signal to the first coast
guardsman coming south at half-past nine, I hear from the dark
levels a sentinel quack, a call. The marsh fills with life again; the
great sun goes south along green treetops and moorlands fruiting
and burned brown.
The quality of life, which in the ardour of spring was personal and
sexual, becomes social in midsummer. Stirred by the vernal fire, a
group psychically dissolves, for every creature in a flock is intent
upon the use and the offering of his own awakened flesh. Even
creatures who are of the flocking or herding habit emerge as
individuals. With the rearing of the young, and their integration into
the reëstablished group, life becomes again a social rhythm. The
body has been given and sacrificially broken, its own gods and all
gods obeyed.

Late Summer on the Dunes

IV
The other day I saw a young swimmer in the surf. He was, I
judged, about twenty-two years old and a little less than six feet tall,
splendidly built, and as he stripped I saw that he must have been
swimming since the season began, for he was sunburned and
brown. Standing naked on the steep beach, his feet in the climbing
seethe, he gathered himself for a swimmer’s crouching spring,
watched his opportunity, and suddenly leaped headfirst through a
long arc of air into the wall of a towering and enormous wave. Again
and again he repeated his jest, emerging each time beyond the
breaker with a stare of salty eyes, a shake of the head, and a smile.
It was all a beautiful thing to see: the surf thundering across the
great natural world, the beautiful and compact body in its naked
strength and symmetry, the astounding plunge across the air, arms
extended ahead, legs and feet together, the emerging stroke of the
flat hands, and the alternate rhythms of the sunburned and powerful
shoulders.
Watching this picture of a fine human being free for the moment of
everything save his own humanity and framed in a scene of nature, I
could not help musing on the mystery of the human body and of how
nothing can equal its rich and rhythmic beauty when it is beautiful or
approach its forlorn and pathetic ugliness when beauty has not been
mingled in or has withdrawn. Poor body, time and the long years
were the first tailors to teach you the merciful use of clothes! Though
some scold to-day because you are too much seen, to my mind, you
are not seen fully enough or often enough when you are beautiful. All
my life it has given me pleasure to see beautiful human beings. To
see beautiful young men and women gives one a kind of reverence
for humanity (alas, of how few experiences may this be said), and
surely there are few moods of the spirit more worthy of our care than
those in which we reverence, even for a moment, our tragic and
bewildered kind.
My swimmer having gone his way, out of a chance curiosity I
picked the top of a dune goldenrod, and found at the very bottom of
a cocoon of twisted leaves the embryo head of the late autumnal
flower.
Chapter X
ORION RISES ON THE DUNES
So came August to its close, ending its last day with a night so
luminous and still that a mood came over me to sleep out on the
open beach under the stars. There are nights in summer when
darkness and ebbing tide quiet the universal wind, and this August
night was full of that quiet of absence, and the sky was clear. South
of my house, between the bold fan of a dune and the wall of a
plateau, a sheltered hollow opens seaward, and to this nook I went,
shouldering my blankets sailorwise. In the star-shine the hollow was
darker than the immense and solitary beach, and its floor was still
pleasantly warm with the overflow of day.
I fell asleep uneasily, and woke again as one wakes out-of-doors.
The vague walls about me breathed a pleasant smell of sand, there
was no sound, and the broken circle of grass above was as
motionless as something in a house. Waking again, hours afterward,
I felt the air grown colder and heard a little advancing noise of
waves. It was still night. Sleep gone and past recapture, I drew on
my clothes and went to the beach. In the luminous east, two great
stars aslant were rising clear of the exhalations of darkness gathered
at the rim of night and ocean—Betelgeuse and Bellatrix, the
shoulders of Orion. Autumn had come, and the Giant stood again at
the horizon of day and the ebbing year, his belt still hidden in the
bank of cloud, his feet in the deeps of space and the far surges of
the sea.
The Fo’castle
My year upon the beach had come full circle; it was time to close
my door. Seeing the great suns, I thought of the last time I marked
them in the spring, in the April west above the moors, dying into the
light and sinking. I saw them of old above the iron waves of black
December, sparkling afar. Now, once again, the Hunter rose to drive
summer south before him, once again autumn followed on his steps.
I had seen the ritual of the sun; I had shared the elemental world.
Wraiths of memories began to take shape. I saw the sleet of the
great storm slanting down again into the grass under the thin
seepage of moon, the blue-white spill of an immense billow on the
outer bar, the swans in the high October sky, the sunset madness
and splendour of the year’s terns over the dunes, the clouds of
beach birds arriving, the eagle solitary in the blue. And because I
had known this outer and secret world, and been able to live as I had
lived, reverence and gratitude greater and deeper than ever
possessed me, sweeping every emotion else aside, and space and
silence an instant closed together over life. Then time gathered
again like a cloud, and presently the stars began to pale over an
ocean still dark with remembered night.
During the months that have passed since that September
morning some have asked me what understanding of Nature one
shapes from so strange a year? I would answer that one’s first
appreciation is a sense that the creation is still going on, that the
creative forces are as great and as active to-day as they have ever
been, and that to-morrow’s morning will be as heroic as any of the
world. Creation is here and now. So near is man to the creative
pageant, so much a part is he of the endless and incredible
experiment, that any glimpse he may have will be but the revelation
of a moment, a solitary note heard in a symphony thundering
through debatable existences of time. Poetry is as necessary to
comprehension as science. It is as impossible to live without
reverence as it is without joy.

Sunrise from Cape Cod


And what of Nature itself, you say—that callous and cruel engine,
red in tooth and fang? Well, it is not so much of an engine as you
think. As for “red in tooth and fang,” whenever I hear the phrase or its
intellectual echoes I know that some passer-by has been getting life
from books. It is true that there are grim arrangements. Beware of
judging them by whatever human values are in style. As well expect
Nature to answer to your human values as to come into your house
and sit in a chair. The economy of nature, its checks and balances,
its measurements of competing life—all this is its great marvel and
has an ethic of its own. Live in Nature, and you will soon see that for
all its non-human rhythm, it is no cave of pain. As I write I think of my
beloved birds of the great beach, and of their beauty and their zest of
living. And if there are fears, know also that Nature has its
unexpected and unappreciated mercies.
Whatever attitude to human existence you fashion for yourself,
know that it is valid only if it be the shadow of an attitude to Nature. A
human life, so often likened to a spectacle upon a stage, is more
justly a ritual. The ancient values of dignity, beauty, and poetry which
sustain it are of Nature’s inspiration; they are born of the mystery
and beauty of the world. Do no dishonour to the earth lest you
dishonour the spirit of man. Hold your hands out over the earth as
over a flame. To all who love her, who open to her the doors of their
veins, she gives of her strength, sustaining them with her own
measureless tremor of dark life. Touch the earth, love the earth,
honour the earth, her plains, her valleys, her hills, and her seas; rest
your spirit in her solitary places. For the gifts of life are the earth’s
and they are given to all, and they are the songs of birds at
daybreak, Orion and the Bear, and dawn seen over ocean from the
beach.

THE END
Transcriber’s Notes
New original cover art included with this eBook is granted to the public domain.

Illustrations have been moved so they do not break up the paragraphs.

Obvious typographical errors and punctuation errors have been corrected after
careful comparison with other occurrences within the text and consultation of
external sources. Except for those changes noted below, all misspellings in the
text, and inconsistent or archaic usage, have been retained.

The following corrections have been applied to the text:

Page Source Correction


xiv BRUNNICH’S ... BRÜNNICH’S ...
24 ... instant or origin, ... ... instant of origin, ...
facing 113 Brunnich’s Murres at Nest ... Brünnich’s Murres at Nest ...
122 ... swept--officers, quarters, ... ... swept--officers’ quarters, ...
161 ... This “alooofe” of the ... ... This “aloofe” of the ...
197 ... Lachnosterna arcuta ... ... Lachnosterna arcuata ...
214 ... I heard from the ... ... I hear from the ...
*** END OF THE PROJECT GUTENBERG EBOOK THE
OUTERMOST HOUSE ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying copyright
royalties. Special rules, set forth in the General Terms of Use part of
this license, apply to copying and distributing Project Gutenberg™
electronic works to protect the PROJECT GUTENBERG™ concept
and trademark. Project Gutenberg is a registered trademark, and
may not be used if you charge for an eBook, except by following the
terms of the trademark license, including paying royalties for use of
the Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is very
easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund from
the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
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!

ebookname.com

You might also like