C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond, Portable Documents

C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond, Portable Documents

by David Abrahams, Aleksey Gurtovoy

NOOK Book(eBook)

$44.99 $47.99 Save 6% Current price is $44.99, Original price is $47.99. You Save 6%.
View All Available Formats & Editions

Available on Compatible NOOK Devices and the free NOOK Apps.
WANT A NOOK?  Explore Now

Product Details

ISBN-13: 9780321623911
Publisher: Pearson Education
Publication date: 12/10/2004
Series: C++ In-Depth Series
Sold by: Barnes & Noble
Format: NOOK Book
Pages: 400
File size: 4 MB

About the Author

David Abrahams is a founding member and moderator of the Boost C++ library development group. Dave has been an ANSI/ISO C++ committee member since 1996, where he is best known for contributing a theory, specification, and implementation of exception handling for the C++ standard library. His company, Boost Consulting, provides Boost-related support and development services and professional training in the art of software construction.

Aleksey Gurtovoy is a technical lead for MetaCommunications and a contributing member of the Boost C++ community. Aleksey is the original author of the Boost Metaprogramming Library. He has been working with C++ since 1993, and holds a M.S. degree in computer science from Krasnoyarsk Technical State University, Russia.

Read an Excerpt

In 1998 Dave had the privilege of attending a workshop in Generic Programming at Dagstuhl Castle in Germany. Near the end of theworkshop, a very enthusiastic Kristof Czarnecki and Ullrich Eisenecker (of Generative Programming fame) passed out a few pages of C++ source code that they billed as a complete Lisp implementation built out of C++ templates. At the time it appeared to Dave to be nothing more than a curiosity, a charming but impractical hijacking of the template system to prove that you can write programs that execute at compile time. He never suspected that one day he would see a role for metaprogramming in most of his day-to-day programming jobs. In many ways, that collection of templates was the precursor to the Boost Metaprogramming Library (MPL): It may have been the first library designed to turn compile-time C++ from an ad hoc collection of "template tricks" into an example of disciplined and readable software engineering. With the availability of tools to write and understand metaprograms at a high level, we've since found that using these techniques is not only practical, but easy, fun, and often astoundingly powerful.

Despite the existence of numerous real systems built with template metaprogramming and the MPL, many people still consider metaprogramming to be other-worldly magic, and often as something to be avoided in day-to-day production code. If you've never done any metaprogramming, it may not even have an obvious relationship to the work you do. With this book, we hope to lift the veil of mystery, so that you get an understanding not only of how metaprogramming is done, but also why and when. The best part is that while much of themystery will have dissolved, we think you'll still find enough magic left in the subject to stay as inspired about it as we are.Making the Most of This Book

The first few chapters of this book lay the conceptual foundation you'll need for most everything else we cover, and chapters generally build on material that has come before. That said, feel free to skip ahead for any reason—we've tried to make that possible by providing cross-references when we use terms introduced earlier on.

Chapter 10, Domain-Specific Embedded Languages, is an exception to the rule that later chapters depend on earlier ones. It focuses mostly on concepts, and only appears late in the book because at that point you'll have learned the tools and techniques to put Domain-Specific Embedded Languages into play in real code. If you only remember one chapter by the time you're done, make it that one.

Near the end of many chapters, you'll find a Details section that summarizes key ideas. These sections usually add new material that deepens the earlier discussion,* so even if you are inclined to skim them the first time through, we suggest you refer back to them later.

We conclude most chapters with exercises designed to help you develop both your programming and conceptual muscles. Those marked with asterisks are expected to be more of a workout than the others. Not all exercises involve writing code—some could be considered "essay questions"—and you don't have to complete them in order to move on to later chapters. We do suggest you look through them, give a little thought to how you'd answer each one, and try your hand at one or two; it's a great way to gain confidence with what you've just read.Supplementary Material

This book comes with a companion CD that supplies the following items in electronic form


  • Sample code from the book.
  • A release of the Boost C++ libraries. Boost has become known for high-quality, peer-reviewed, portable, generic, and freely reusable C++ libraries. We make extensive use of one Boost library throughout the book—the Boost Metaprogramming Library (MPL)—and we discuss several others.
  • A complete MPL reference manual, in HTML and PDF form.
  • Boost libraries discussed in this book that are not yet part of an official release.

The index.html file at the top level of the CD will provide you with a convenient guide to all of its contents. Additional and updated material, including the inevitable errata, will appear on the book's Web site: http://www.boost-consulting.com/mplbook. You'll also find a place there to report any mistakes you might find.Trying It Out

To compile any of the examples, just put the CD's boost 1 32 0/ directory into your compiler's #include path.

The libraries we present in this book go to great lengths to hide the problems of less-than-perfect compilers, so it's unlikely that you'll have trouble with the examples we present here. That said, we divide C++ compilers roughly into three categories.

A. Those with mostly conforming template implementations. On these compilers, the examples and libraries "just work." Almost anything released since 2001, and a few compilers released before then, fall into this category.
B. Those that can be made to work, but require some workarounds in user code.
C. Those that are too broken to use effectively for template metaprogramming.

Appendix D lists the compilers that are known to fall into each of these categories. For those in category B, Appendix D refers to a list of portability idioms. These idioms have been applied to the copies of the book's examples that appear on the accompanying CD, but to avoid distracting the majority of readers they don't appear in the main text.

The CD also contains a portability table with a detailed report of how various compilers are doing with our examples. GCC is available free for most platforms, and recent versions have no problems handling the code we present here.

Even if you have a relatively modern compiler from category A, it might be a good idea to grab a copy of GCC with which to cross-check your code. Often the easiest way to decipher an inscrutable error message is to see what some other compiler has to say about your program. If you find yourself struggling with error messages as you try to do the exercises, you might want to skip ahead and read the first two sections of Chapter 8, which discusses how to read and manage diagnostics.

And now, on to C++ Template Metaprogramming!

— Dave and Aleksey

* We borrowed this idea from Andrew Koenig and Barbara Moo's Accelerated C++: Practical Programming By Example.

0321227255P12142004

Table of Contents

Preface.

Acknowledgments.

Making the Most of This Book.

1. Introduction.

Getting Started.

So What's a Metaprogram?

Metaprogramming in the Host Language.

Metaprogramming in C++.

Why Metaprogramming?

When Metaprogramming?

Why a Metaprogramming Library?

2. Traits and Type Manipulation.

Type Associations.

Metafunctions.

Numerical Metafunctions.

Making Choices at Compile Time.

A Brief Tour of the Boost Type Traits Library.

Nullary Metafunctions.

Metafunction Definition.

History.

Details.

Exercises.

3. A Deeper Look at Metafunctions.

Dimensional Analysis.

Higher-Order Metafunctions.

Handling Placeholders.

More Lambda Capabilities.

Lambda Details.

Details.

Exercises.

4. Integral Type Wrappers and Operations.

Boolean Wrappers and Operations.

Integer Wrappers and Operations.

Exercises.

5. Sequences and Iterators.

Concepts.

Sequences and Algorithms.

Iterators.

Iterator Concepts.

Sequence Concepts.

Sequence Equality.

Intrinsic Sequence Operations.

Sequence Classes.

Integral Sequence Wrappers.

Sequence Derivation.

Writing Your Own Sequence.

Details.

Exercises.

6. Algorithms.

Algorithms, Idioms, Reuse, and Abstraction.

Algorithms in the MPL.

Inserters.

Fundamental Sequence Algorithms.

Querying Algorithms.

Sequence Building Algorithms.

Writing Your Own Algorithms.

Details.

Exercises.

7. Views and Iterator Adaptors.

A Few Examples.

View Concept.

Iterator Adaptors.

Writing Your Own View.

History.

Exercises.

8. Diagnostics.

Debugging the Error Novel.

Using Tools for Diagnostic Analysis.

Intentional Diagnostic Generation.

History.

Details.

Exercises.

9. Crossing the Compile-Time/Runtime Boundary.

for each.

Implementation Selection.

Object Generators.

Structure Selection.

Class Composition.

(Member) Function Pointers as Template Arguments.

Type Erasure.

The Curiously Recurring Template Pattern.

Explicitly Managing the Overload Set.

The "sizeof Trick".

Summary.

Exercises.

10. Domain-Specific Embedded Languages.

A Little Language.

Goes a Long Way.

DSLs, Inside Out.

C++ as the Host Language.

Blitz++ and Expression Templates.

General-Purpose DSELs.

The Boost Spirit Library.

Summary.

Exercises.

11. A DSEL DesignWalkthrough.

Finite State Machines.

Framework Design Goals.

Framework Interface Basics.

Choosing a DSL.

Implementation.

Analysis.

Language Directions.

Exercises.

Appendix A. An Introduction to Preprocessor Metaprogramming.

Motivation.

Fundamental Abstractions of the Preprocessor.

Preprocessor Library Structure.

Preprocessor Library Abstractions.

Exercise.

Appendix B. The typename and template Keywords.

The Issue.

The Rules.

Appendix C. Compile-Time Performance.

The Computational Model.

Managing Compilation Time.

The Tests.

Appendix D. MPL Portability Summary.

Bibliography.

Index.

Introduction

In 1998 Dave had the privilege of attending a workshop in Generic Programming at Dagstuhl Castle in Germany. Near the end of theworkshop, a very enthusiastic Kristof Czarnecki and Ullrich Eisenecker (of Generative Programming fame) passed out a few pages of C++ source code that they billed as a complete Lisp implementation built out of C++ templates. At the time it appeared to Dave to be nothing more than a curiosity, a charming but impractical hijacking of the template system to prove that you can write programs that execute at compile time. He never suspected that one day he would see a role for metaprogramming in most of his day-to-day programming jobs. In many ways, that collection of templates was the precursor to the Boost Metaprogramming Library (MPL): It may have been the first library designed to turn compile-time C++ from an ad hoc collection of "template tricks" into an example of disciplined and readable software engineering. With the availability of tools to write and understand metaprograms at a high level, we've since found that using these techniques is not only practical, but easy, fun, and often astoundingly powerful.

Despite the existence of numerous real systems built with template metaprogramming and the MPL, many people still consider metaprogramming to be other-worldly magic, and often as something to be avoided in day-to-day production code. If you've never done any metaprogramming, it may not even have an obvious relationship to the work you do. With this book, we hope to lift the veil of mystery, so that you get an understanding not only of how metaprogramming is done, but also why and when. The best part is that while much ofthe mystery will have dissolved, we think you'll still find enough magic left in the subject to stay as inspired about it as we are.

Making the Most of This Book

The first few chapters of this book lay the conceptual foundation you'll need for most everything else we cover, and chapters generally build on material that has come before. That said, feel free to skip ahead for any reason—we've tried to make that possible by providing cross-references when we use terms introduced earlier on.

Chapter 10, Domain-Specific Embedded Languages, is an exception to the rule that later chapters depend on earlier ones. It focuses mostly on concepts, and only appears late in the book because at that point you'll have learned the tools and techniques to put Domain-Specific Embedded Languages into play in real code. If you only remember one chapter by the time you're done, make it that one.

Near the end of many chapters, you'll find a Details section that summarizes key ideas. These sections usually add new material that deepens the earlier discussion,* so even if you are inclined to skim them the first time through, we suggest you refer back to them later.

We conclude most chapters with exercises designed to help you develop both your programming and conceptual muscles. Those marked with asterisks are expected to be more of a workout than the others. Not all exercises involve writing code—some could be considered "essay questions"—and you don't have to complete them in order to move on to later chapters. We do suggest you look through them, give a little thought to how you'd answer each one, and try your hand at one or two; it's a great way to gain confidence with what you've just read.

Supplementary Material

This book comes with a companion CD that supplies the following items in electronic form

  • Sample code from the book.
  • A release of the Boost C++ libraries. Boost has become known for high-quality, peer-reviewed, portable, generic, and freely reusable C++ libraries. We make extensive use of one Boost library throughout the book—the Boost Metaprogramming Library (MPL)—and we discuss several others.
  • A complete MPL reference manual, in HTML and PDF form.
  • Boost libraries discussed in this book that are not yet part of an official release.

The index.html file at the top level of the CD will provide you with a convenient guide to all of its contents. Additional and updated material, including the inevitable errata, will appear on the book's Web site. You'll also find a place there to report any mistakes you might find.

Trying It Out

To compile any of the examples, just put the CD's boost 1 32 0/ directory into your compiler's #include path.

The libraries we present in this book go to great lengths to hide the problems of less-than-perfect compilers, so it's unlikely that you'll have trouble with the examples we present here. That said, we divide C++ compilers roughly into three categories.

      A. Those with mostly conforming template implementations. On these compilers, the examples and libraries "just work." Almost anything released since 2001, and a few compilers released before then, fall into this category.
      B. Those that can be made to work, require some workarounds in user code.
      C. Those that are too broken to use effectively for template metaprogramming.

Appendix D lists the compilers that are known to fall into each of these categories. For those in category B, Appendix D refers to a list of portability idioms. These idioms have been applied to the copies of the book's examples that appear on the accompanying CD, but to avoid distracting the majority of readers they don't appear in the main text.

The CD also contains a portability table with a detailed report of how various compilers are doing with our examples. GCC is available free for most platforms, and recent versions have no problems handling the code we present here.

Even if you have a relatively modern compiler from category A, it might be a good idea to grab a copy of GCC with which to cross-check your code. Often the easiest way to decipher an inscrutable error message is to see what some other compiler has to say about your program. If you find yourself struggling with error messages as you try to do the exercises, you might want to skip ahead and read the first two sections of Chapter 8, which discusses how to read and manage diagnostics.

And now, on to C++ Template Metaprogramming!

— Dave and Aleksey

* We borrowed this idea from Andrew Koenig and Barbara Moo's Accelerated C++: Practical Programming By Example.

Customer Reviews

Most Helpful Customer Reviews

See All Customer Reviews

C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond 4.5 out of 5 based on 0 ratings. 2 reviews.
_Greg on LibraryThing More than 1 year ago
Type-based (template) metaprogramming is one of the most powerful programming technologies available. Its also highly mind-expanding. If you're a true geek and you have a strong background in C++ this is for you. Otherwise, forget it!
Guest More than 1 year ago
It was only some 5 or 6 years ago that templates became standardised in C++. Even now, frustratingly, different C++ compilers may still have slightly different treatments. That notwithstanding, templates have been widely recognised as enhancing the expressive power of C++. But the authors reveal that perhaps you have not fully appreciated just how expressive templates can be. They aim this book at experienced C++ programmers. Who still probably have not used templates beyond the standard examples. The metaprogramming in the book goes on at compile time, not run time. Previously, explicit user directives at compile time might have been parser type commands, along the lines of YACC. But templates open up this compile time to a wide new space of manipulations. While the authors were not the first to discover it, the book appears to be one of the first to promulgate the idea. The book is replete with examples of programming these templates. Some of you will thrill to explore it. But others may find it very confining. Because data is immutable. So compile time C++ has no analog of the non-constant variables used in run time C++. This immediately rules out for loops, for starters. Instead, recursion is often used in place of for. It's a different mind set to cultivate. Metaprogramming is intriguing, but its utility may be only in a few circumstances.