<?xml version="1.0" encoding="utf-8"?><FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>comp_programming</genre><author><first-name>Bruce</first-name><last-name>Eckel</last-name></author><author><first-name>Chuck</first-name><last-name> Allison</last-name></author><book-title>Thinking In C++. Volume 2: Practical Programming</book-title><annotation><p>Best selling author Bruce Eckel has joined forces with Chuck Allison to write <emphasis>Thinking in C++, Volume 2</emphasis>, the sequel to the highly received and best selling <emphasis>Thinking in C++, Volume 1</emphasis>. Eckel is the master of teaching professional programmers how to quickly learn cutting edge topics in C++ that are glossed over in other C++ books. In <emphasis>Thinking in C++, Volume 2</emphasis>, the authors cover the finer points of exception handling, defensive programming and string and stream processing that every C++ programmer needs to know. Special attention is given to generic programming where the authors reveal little known techniques for effectively using the Standard Template Library. In addition, Eckel and Allison demonstrate how to apply RTTI, design patterns and concurrent programming techniques to improve the quality of industrial strength C++ applications. This book is targeted at programmers of all levels of experience who want to master C++. </p></annotation><keywords>C++</keywords><date>2003</date><coverpage><image l:href="#cover"/></coverpage><lang>en</lang></title-info><document-info><author><nickname>Ulenspiegel</nickname></author><program-used>ExportToFB21, FictionBook Editor Release 2.6, fb2cut 2.5.4, fb2cut 2.6.2</program-used><date value="2010-11-30">11/30/2010</date><id>OOoFBTools-2010-11-30-17-55-41-568</id><version>1.03</version></document-info><publish-info><book-name>Thinking In C++. Volume 2: Practical Programming</book-name><publisher>Prentice Hall</publisher><year>2003</year><isbn>978-0130353139</isbn></publish-info></description><body><title><p>Thinking In C++. Volume 2: Practical Programming</p></title><epigraph><p>To all those who have worked tirelessly on the development of the C++ language</p></epigraph><section><title><p>Preface</p></title><section><p>In Volume 1 of this book, you learn the fundamentals of C and C++. In this volume, we look at more advanced features, with an eye towards developing techniques and ideas that produce robust C++ programs.</p><p>Thus, in this volume we are assuming that you are familiar with the material developed in Volume 1<sup>.</sup></p></section><section><title><p>Goals</p></title><p>Our goals in this book are to:<sup>.</sup></p><p>1. Present the material a simple step at a time, so the reader can easily digest each concept before moving on.</p><p>2. Teach «practical programming» techniques that you can use on a day-to-day basis.</p><p>3. Give you what we think is important for you to understand about the language, rather than everything we know. We believe there is an «information importance hierarchy,» and there are some facts that 95% of programmers will never need to know, but that would just confuse people and add to their perception of the complexity of the language. To take an example from C, if you memorize the operator precedence table (we never did) you can write clever code. But if <emphasis>you</emphasis> have to think about it, it will confuse the reader/maintainer of that code. So forget about precedence, and use parentheses when things aren’t clear. This same attitude will be taken with some information in the C++ language, which is more important for compiler writers than for programmers.</p><p>4. Keep each section focused enough so the lecture time—and the time between exercise periods—is small. Not only does this keep the audience’ minds more active and involved during a hands-on seminar, but it gives the reader a greater sense of accomplishment.</p><p>5. We have endeavored not to use any particular vendor’s version of C++. We have tested the code on all the implementations we could, and when one implementation absolutely refused to work because it doesn’t conform to the C++ Standard, we’ve flagged that fact in the example (you’ll see the flags in the source code) to exclude it from the build process.</p><p>6. Automate the compiling and testing of the code in the book. We have discovered that code that isn’t compiled and tested is probably broken, so in this volume we’ve instrumented the examples with test code. In addition, the code that you can download from http://www.MindView.net has been extracted directly from the text of the book using programs that also automatically create makefiles to compile and run the tests. This way we know that the code in the book is correct.</p></section><section><title><p>Chapters</p></title><p>Here is a brief description of the chapters contained in this book:</p><p><strong>Part 1: Building Stable Systems</strong></p><p><strong>1. Exception handling</strong>. Error handling has always been a problem in programming. Even if you dutifully return error information or set a flag, the function caller may simply ignore it. Exception handling is a primary feature in C++ that solves this problem by allowing you to «throw» an object out of your function when a critical error happens. You throw different types of objects for different errors, and the function caller «catches» these objects in separate error handling routines. If you throw an exception, it cannot be ignored, so you can guarantee that <emphasis>something</emphasis> will happen in response to your error. The decision to use exceptions (a good one!) affects code design in fundamental ways<sup>.</sup></p><p><strong>2. Defensive Programming.</strong> Many software problems can be prevented. To program defensively is to craft code in such a way that bugs can be found and fixed early before they have a chance to do damage in the field. The use of assertions is the single most important thing you can do to validate your code during development, while at the same time leaving an executable documentation trail in your code that reveals what you were thinking when you wrote the code in the first place. Before you let your code out of your hands it should be rigorously tested. A framework for automated unit testing is an indispensable tool for successful, everyday software development.</p><p><strong>Part 2: The Standard C++ Library</strong></p><p><strong>3. Strings in Depth.</strong> Text processing is the most common programming activity by far. The C++ string class relieves the programmer from memory management issues, while at the same time delivering a powerhouse of text processing capability. C++ also supports the use of wide characters and locales for internationalized applications.</p><p><strong>4. Iostreams</strong>. One of the original C++ libraries—the one that provides the essential I/O facility—is called iostreams. Iostreams is intended to replace C’s <strong>stdio.h </strong>with an I/O library that is easier to use, more flexible, and extensible—you can adapt it to work with your new classes. This chapter teaches you the ins and outs of how to make the best use of the existing iostream library for standard I/O, file I/O, and in-memory formatting<sup>.</sup></p><p><strong>5. Templates in Depth.</strong> The distinguishing feature of «modern C++» is the broad power of templates. Templates are for more than just generic containers; they support development of robust, generic, high-performance libraries. There is a lot to know about templates—they constitute, as it were, a sub-language within the C++ language, and give the programmer an impressive degree of control over the compilation process. It is not an understatement to say that templates have revolutionized C++ programming.</p><p><strong>6. Generic Algorithms.</strong> Algorithms are at the core of computing, and C++, through its template facility, supports an impressive entourage of powerful, efficient, and easy-to-use generic algorithms. The standard algorithms are also customizable through function objects. This chapter looks at every algorithm in the library. (Chapters 6 and 7 cover that portion of the standard C++ library commonly-known as the Standard Template Library, or STL.)</p><p><strong>7. Generic Containers &amp; Iterators</strong>. C++ supports all the common data structures known to man in a type-safe manner. You never have to worry about what such a container holds; the homogeneity of its objects is guaranteed. Separating the traversing of a container from the container itself, another accomplishment of templates, is made possible through iterators. This ingenious arrangement allows a flexible application of algorithms to containers by means of the simplest of designs.</p><p><strong>Part 3: Special Topics</strong></p><p><strong>8. Run-time type identification</strong>. Run-time type identification (RTTI) lets you find the exact type of an object when you only have a pointer or reference to the base type. Normally, you’ll want to intentionally ignore the exact type of an object and let the virtual function mechanism implement the correct behavior for that type. But occasionally (like when writing software tools such as debuggers) it is helpful to know the exact type of an object for which you only have a base pointer; often this information allows you to perform a special-case operation more efficiently. This chapter explains what RTTI is for and how to use it<sup>.</sup></p><p><strong>9. Multiple inheritance</strong>. This sounds simple at first: A new class is inherited from more than one existing class. However, you can end up with ambiguities and multiple copies of base-class objects. That problem is solved with virtual base classes, but the bigger issue remains: When do you use it? Multiple inheritance is only essential when you need to manipulate an object through more than one common base class. This chapter explains the syntax for multiple inheritance, and shows alternative approaches—in particular, how templates solve one common problem. The use of multiple inheritance to repair a «damaged» class interface is demonstrated as a genuinely valuable use of this feature<sup>.</sup></p><p><strong>10. Design Patterns.</strong> The most revolutionary advance in programming since objects is the introduction of <emphasis>design patterns</emphasis>. A design pattern is a language-independent codification of a solution to a common programming problem, expressed in such a way that it can apply to many contexts. Patterns such as Singleton, Factory Method, and Visitor now find their way into daily discussions around the keyboard. This chapter shows how to implement and use some of the more useful design patterns in C++.</p><p><strong>11. Concurrent Programming.</strong> Users have long been used to responsive user interfaces that (seem to) process multiple tasks simultaneously. Modern operating systems allow processes to have multiple threads that share the process address space. Multi-threaded programming requires a different mindset, however, and comes with its own set of «gotchas.» This chapter uses a freely available library (the ZThread library by Eric Crahen of IBM) to show how to effectively manage multi-threaded applications in C++.</p></section><section><title><p>Exercises</p></title><p>We have discovered that simple exercises are exceptionally useful during a seminar to complete a student’s understanding, so you’ll find a set at the end of each chapter<sup>.</sup></p><p>These are fairly simple, so they can be finished in a reasonable amount of time in a classroom situation while the instructor observes, making sure all the students are absorbing the material. Some exercises are a bit more challenging to keep advanced students entertained. They’re all designed to be solved in a short time and are only there to test and polish your knowledge rather than present major challenges (presumably, you’ll find those on your own—or more likely they’ll find you).</p></section><section><title><p>Exercise solutions</p></title><p>Solutions to exercises can be found in the electronic document <emphasis>The C++ Annotated Solution Guide</emphasis>, Volume 2, available for a nominal fee from <a l:href="http://www.bruceeckel.com/">www.MindView.net</a><sup>.</sup></p></section><section><title><p>Source code</p></title><p>The source code for this book is copyrighted freeware, distributed via the web site http://www.MindView.net. The copyright prevents you from republishing the code in print media without permission<sup>.</sup></p><p>In the starting directory where you unpacked the code you will find the following copyright notice:<sup>.</sup></p><p>//:! :CopyRight.txt</p><p>Copyright (c) MindView, Inc., 2003</p><p>Source code file from the book</p><p>«Thinking in C++, 2nd Edition, Volume 2.»</p><p>All rights reserved EXCEPT as allowed by the</p><p>following statements: You can freely use this file</p><p>for your own work (personal or commercial),</p><p>including modifications and distribution in</p><p>executable form only. Permission is granted to use</p><p>this file in classroom situations, including its</p><p>use in presentation materials, as long as the book</p><p>«Thinking in C++» is cited as the source.</p><p>Except in classroom situations, you cannot copy</p><p>and distribute this code; instead, the sole</p><p>distribution point is http://www.MindView.net</p><p>(and official mirror sites) where it is</p><p>freely available. You cannot remove this</p><p>copyright and notice. You cannot distribute</p><p>modified versions of the source code in this</p><p>package. You cannot use this file in printed</p><p>media without the express permission of the</p><p>author. The authors makes no representation about</p><p>the suitability of this software for any purpose.</p><p>It is provided «as is» without express or implied</p><p>warranty of any kind, including any implied</p><p>warranty of merchantability, fitness for a</p><p>particular purpose or non-infringement. The entire</p><p>risk as to the quality and performance of the</p><p>software is with you. The authors and publisher shall not be liable for any damages suffered by you or any third party as a result of using or distributing software. In no event will the authors or the publisher be liable for any</p><p>lost revenue, profit, or data, or for direct,</p><p>indirect, special, consequential, incidental, or</p><p>punitive damages, however caused and regardless of</p><p>the theory of liability, arising out of the use of</p><p>or inability to use software, even if Bruce Eckel</p><p>and the publisher have been advised of the</p><p>possibility of such damages. Should the software</p><p>prove defective, you assume the cost of all</p><p>necessary servicing, repair, or correction. If you</p><p>think you've found an error, please submit the</p><p>correction using the form you will find at</p><p>www.MindView.net. (Please use the same</p><p>form for non-code errors found in the book.)</p><p>///:~</p><empty-line/><p>You may use the code in your projects and in the classroom as long as the copyright notice is retained<sup>.</sup></p></section><section><title><p>Language standards</p></title><p>Throughout this book, when referring to conformance to the ANSI/ISO C standard, we will be referring to the 1989 standard, and will generally just say ‘<strong>C</strong>.’ Only if it is necessary to distinguish between Standard 1989 C and older, pre-Standard versions of C will we make the distinction. We do not reference C99 in this book<sup>.</sup></p><p>As this book goes to press the ANSI/ISO C++ committee has long ago finished working on the first C++ standard, commonly known as C++98. We will use the term <emphasis>Standard C++</emphasis> to refer to this standardized language. If we simply refer to C++, assume we mean «Standard C++.» The C++ standards committee continues to address issues important to the C++ community that will find expression in C++0x, a future C++ standard not likely to be available for many years<sup>.</sup></p></section><section><title><p>Language support</p></title><p>Your compiler may not support all the features discussed in this book, especially if you don’t have the newest version of your compiler. Implementing a language like C++ is a Herculean task, and you can expect that the features will appear in pieces rather than all at once. But if you attempt one of the examples in the book and get a lot of errors from the compiler, it’s not necessarily a bug in the code or the compiler—it may simply not be implemented in your particular compiler yet. On the Windows platform we have validated all examples with the C++ compiler found in Microsoft’s Visual Studio .NET 2003; Borland C++ Builder version 6; the GNU projects g++ compiler, version 3.2, running under Cygwin; and the Edison Design Group’s C++ front end using the Dinkumware full C++ library. We have also run all the examples on Mac OS X with Metrowerks C++ version 8. In those instances where a compiler does not support the feature required by a sample program, we have so indicated in comments in the source code<sup>.</sup></p></section><section><title><p>Seminars, CD-ROMs &amp; consulting</p></title><p>Bruce Eckel’s company, MindView, Inc., provides public hands-on training seminars based on the material in this book, and also for advanced topics. Selected material from each chapter represents a lesson, which is followed by a monitored exercise period so each student receives personal attention. We also provide on-site training, consulting, mentoring, and design &amp; code walkthroughs. Information and sign-up forms for upcoming seminars and other contact information can be found at <strong>http://www.MindView.net</strong><sup><strong>.</strong></sup></p></section><section><title><p>Errors</p></title><p>No matter how many tricks a writer uses to detect errors, some always creep in and these often leap off the page for a fresh reader. If you discover anything you believe to be an error, please use the feedback system built into the electronic version of this book, which you will find at <strong>http://www.MindView.net</strong>. The feedback system uses unique identifiers on the paragraphs in the book, so click on the identifier next to the paragraph that you wish to comment on. Your help is appreciated<sup>.</sup></p></section><section><title><p>About the cover</p></title><p>The cover artwork was painted by Larry O’Brien’s wife, Tina Jensen (yes, the Larry O’Brien who was the editor of Software Development Magazine for so many years). Not only are the pictures beautiful, but they are excellent suggestions of polymorphism. The idea for using these images came from Daniel Will-Harris, the cover designer (www.Will-Harris.com), working with Bruce Eckel.</p></section><section><title><p>Acknowledgements</p></title><p>Volume 2 of this book languished in a half-completed state for a long time while Bruce got distracted with other things, notably Java, Design Patterns and especially Python (see www.Python.org). If Chuck hadn’t been willing (foolishly, he has sometimes thought) to finish the other half and bring things up-to-date, this book almost certainly wouldn’t have happened. There aren’t that many people whom Bruce would have felt comfortable entrusting this book to. Chuck’s penchant for precision, correctness and clear explanation is what has made this book as good as it is.</p><p>Jamie King acted as an intern under Chuck’s direction during the completion of this book. He was instrumental in making sure the book got finished, not only by providing feedback for Chuck, but especially because of his relentless questioning and picking of every single possible nit that he didn’t completely understand. If your questions are answered by this book, it’s probably because Jamie asked them first. Jamie also enhanced a number of the sample programs and created many of the exercises at the end of each chapter.</p><p>Eric Crahen of IBM was instrumental in the completion of Chapter 11 (Concurrent Programming). When we were looking for a threads package, we sought out one that was intuitive and easy to use, while being sufficiently robust to do the job. With Eric we got that and then some—he was extremely cooperative and has used our feedback to enhance his library, while we have benefited from his insights as well.</p><p>We are grateful to have had Pete Becker as a technical editor. Few people are as articulate and discriminating as Pete, not to mention as expert in C++ and software development in general. We also thank Bjorn Karlsson for his gracious and timely technical assistance as he reviewed the entire manuscript with little notice.</p><p>The ideas and understanding in this book have come from many other sources, as well: friends like Andrea Provaglio, Dan Saks, Scott Meyers, Charles Petzold, and Michael Wilk; pioneers of the language like Bjarne Stroustrup, Andrew Koenig, and Rob Murray; members of the C++ Standards Committee like Nathan Myers (who was particularly helpful and generous with his insights), Herb Sutter, PJ Plauger, Pete Becker, Kevlin Henney, David Abrahams, Tom Plum, Reg Charney, Tom Penello, Sam Druker, and Uwe Steinmueller, John Spicer, Steve Adamczyk, and Daveed Vandevoorde; people who have spoken in the C++ track at the Software Development Conference (which Bruce created and developed, and Chuck spoke in); and often students in seminars, who ask the questions we need to hear to make the material clearer<sup>.</sup></p><p>The book design, cover design, and cover photo were created by Bruce’s friend Daniel Will-Harris, noted author and designer, who used to play with rub-on letters in junior high school while he awaited the invention of computers and desktop publishing. However, we produced the camera-ready pages ourselves, so the typesetting errors are ours. Microsoft<sup>®</sup> Word XP was used to write the book and to create camera-ready pages. The body typeface is Georgia and the headlines are in Verdana. The code type face is Andale Mono<sup>.</sup></p><p>We also wish to thank the generous professionals at the Edison Design Group and Dinkumware, Ltd., for giving us complimentary copies of their compiler and library (respectively). Without their assistance some of the examples in this book could not have been tested. We also wish to thank Howard Hinnant and the folks at Metrowerks for a copy of their compiler, and Sandy Smith and the folks at SlickEdit for keeping Chuck supplied with a world-class editing environment for so many years. Greg Comeau also provided a copy of his successful EDG-based compiler, Comeau C++.</p><p>A special thanks to all our teachers, and all our students (who are our teachers as well).</p><p>Evan Cofsky (Evan@TheUnixMan.com) provided all sorts of assistance on the server as well as development of programs in his now-favorite language, Python. Sharlynn Cobaugh and Paula Steuer were instrumental assistants, preventing Bruce from being washed away in a flood of projects.</p><p>Dawn McGee provided much-appreciated inspiration and enthusiasm during this project. The supporting cast of friends includes, but is not limited to: Mark Western, Gen Kiyooka, Kraig Brockschmidt, Zack Urlocker, Andrew Binstock, Neil Rubenking, Steve Sinofsky, JD Hildebrandt, Brian McElhinney, Brinkley Barr, Bill Gates at Midnight Engineering Magazine, Larry Constantine &amp; Lucy Lockwood, Tom Keffer, Greg Perry, Dan Putterman, Christi Westphal, Gene Wang, Dave Mayer, David Intersimone, Claire Sawyers, The Italians (Andrea Provaglio, Laura Fallai, Marco Cantu, Michael Seaver, Huston Franklin, David Wagstaff, Corrado, Ilsa and Christina Giustozzi), Chris &amp; Laura Strand, The Almquists, Brad Jerbic, John Kruth &amp; Marilyn Cvitanic, Holly Payne (yes, the famous novelist!), Mark Mabry, The Robbins Families, The Moelter Families (&amp; the McMillans), The Wilks, Dave Stoner, Laurie Adams, The Cranstons, Larry Fogg, Mike &amp; Karen Sequeira, Gary Entsminger &amp; Allison Brody, Chester Andersen, Joe Lordi, Dave &amp; Brenda Bartlett, The Rentschlers, The Sudeks, Lynn &amp; Todd, and their families. And of course, Mom &amp; Dad, Sandy, James &amp; Natalie, Kim&amp; Jared, Isaac, and Abbi. </p></section></section><section><title><p>Part 1.Building Stable Systems</p></title><section><empty-line/><p>Software engineers spend about as much time validating code as they do creating it. Quality is or should be the goal of every programmer, and one can go a long way towards that goal by eliminating problems before they rear their ugly heads. In addition, software systems should be robust enough to behave reasonably in the presence of unforeseen environmental problems.</p><p>Exception handling was introduced into C++ to support sophisticated error handling without cluttering code with an inordinate amount of error-handling logic. Chapter 1 shows how proper use of exceptions can make for well-behaved software, and also introduces the design principles that underlie exception-safe code. In Chapter 2 we cover unit testing and debugging techniques intended to maximize code quality long before it’s released. The use of assertions to express and enforce program invariants is a sure sign of an experienced software engineer. We also introduce a simple framework to help mitigate the tedium of unit testing.</p></section><section><title><p>1: Exception handling</p></title><section><p>Improving error recovery is one of the most powerful ways you can increase the robustness of your code.</p><p>Unfortunately, it’s almost accepted practice to ignore error conditions, as if we’re in a state of denial about errors. One reason, no doubt, is the tediousness and code bloat of checking for many errors. For example, <strong>printf( )</strong> returns the number of characters that were successfully printed, but virtually no one checks this value. The proliferation of code alone would be disgusting, not to mention the difficulty it would add in reading the code<sup>.</sup></p><p>The problem with C’s approach to error handling could be thought of as coupling—the user of a function must tie the error-handling code so closely to that function that it becomes too ungainly and awkward to use<sup>.</sup></p><p>One of the major features in C++ is <emphasis>exception handling</emphasis>, which is a better way of thinking about and handling errors. With exception handling the following statements apply:<sup>.</sup></p><p>1.Error-handling code is not nearly so tedious to write, and it doesn't become mixed up with your «normal» code. You write the code you <emphasis>want</emphasis> to happen; later in a separate section you write the code to cope with the problems. If you make multiple calls to a function, you handle the errors from that function once, in one place.</p><p>2.Errors cannot be ignored. If a function needs to send an error message to the caller of that function, it «throws» an object representing that error out of the function. If the caller doesn’t «catch» the error and handle it, it goes to the next enclosing dynamic scope, and so on until the error is either caught or the program terminates because there was no handler to catch that type of exception.</p><p>This chapter examines C’s approach to error handling (such as it is), discusses why it did not work well for C, and explains why it won’t work at all for C++. This chapter also covers <strong>try</strong>, <strong>throw</strong>, and <strong>catch</strong>, the C++ keywords that support exception handling<sup>.</sup></p></section><section><title><p>Traditional error handling</p></title><p>In most of the examples in these volumes, we use <strong>assert( )</strong> as it was intended: for debugging during development with code that can be disabled with <strong>#define NDEBUG</strong> for the shipping product. Runtime error checking uses the <strong>require.h</strong> functions (<strong>assure( )</strong> and <strong>require( )</strong>) developed in Chapter 9 in Volume 1. These functions are a convenient way to say, «There’s a problem here you’ll probably want to handle with some more sophisticated code, but you don’t need to be distracted by it in this example.» The <strong>require.h</strong> functions might be enough for small programs, but for complicated products you might need to write more sophisticated error-handling code<sup>.</sup></p><p>Error handling  quite straightforward in situations in which you know exactly what to do because you have all the necessary information in that context. Of course, you just handle the error at that point<sup>.</sup></p><p>The problem occurs when you <emphasis>don’t</emphasis> have enough information in that context, and you need to pass the error information into a different context where that information does exist. In C, you can handle this situation using three approaches:<sup>.</sup></p><p>1.Return error information from the function or, if the return value cannot be used this way, set a global error condition flag. (Standard C provides <strong>errno</strong> and <strong>perror( )</strong> to support this.) As mentioned earlier, the programmer is likely to ignore the error information because tedious and obfuscating error checking must occur with each function call. In addition, returning from a function that hits an exceptional condition might not make sense.</p><p>2.Use the little-known Standard C library signal-handling system, implemented with the <strong>signal( )</strong> function (to determine what happens when the event occurs) and <strong>raise( )</strong> (to generate an event). Again, this approach involves high coupling because it requires the user of any library that generates signals to understand and install the appropriate signal-handling mechanism; also in large projects the signal numbers from different libraries might clash.</p><p>3.Use the <emphasis>nonlocal goto</emphasis> functions in the Standard C library: <strong>setjmp( )</strong> and <strong>longjmp( )</strong>. With <strong>setjmp( )</strong> you save a known good state in the program, and if you get into trouble, <strong>longjmp( )</strong> will restore that state. Again, there is high coupling between the place where the state is stored and the place where the error occurs.</p><p>When considering error-handling schemes with C++, there’s an additional critical problem: The C techniques of signals and <strong>setjmp( )</strong>/<strong>longjmp( )</strong> do not call destructors, so objects aren’t properly cleaned up. (In fact, if <strong>longjmp( )</strong> jumps past the end of a scope where destructors should be called, the behavior of the program is undefined.) This makes it virtually impossible to effectively recover from an exceptional condition because you’ll always leave objects behind that haven’t been cleaned up and that can no longer be accessed. The following example demonstrates this with <strong>setjmp/longjmp</strong>:<sup>.</sup></p><p><code>//: C01:Nonlocal.cpp</code></p><p><code>// setjmp() &amp; longjmp()</code></p><p><code>#include &lt;iostream&gt;</code></p><p><code>#include &lt;csetjmp&gt;</code></p><p><code>using namespace std;</code></p><empty-line/><p><code>class Rainbow {</code></p><p><code>public:</code></p><p><code>  Rainbow() { cout &lt;&lt; «Rainbow()» &lt;&lt; endl; }</code></p><p><code>  ~Rainbow() { cout &lt;&lt; «~Rainbow()» &lt;&lt; endl; }</code></p><p><code>};</code></p><empty-line/><p><code>jmp_buf kansas;</code></p><empty-line/><p><code>void oz() {</code></p><p><code>  Rainbow rb;</code></p><p><code>  for(int i = 0; i &lt; 3; i++)</code></p><p><code>    cout &lt;&lt; «there's no place like home\n»;</code></p><p><code>  longjmp(kansas, 47);</code></p><p><code>}</code></p><empty-line/><p><code>int main() {</code></p><p><code>  if(setjmp(kansas) == 0) {</code></p><p><code>    cout &lt;&lt; «tornado, witch, munchkins...\n»;</code></p><p><code>    oz();</code></p><p><code>  } else {</code></p><p><code>    cout &lt;&lt; «Auntie Em! "</code></p><p><code>         &lt;&lt; "I had the strangest dream..."</code></p><p><code>         &lt;&lt; endl;</code></p><p><code>  }</code></p><p>} ///:~</p><empty-line/><p>The <strong>setjmp( )</strong> function is odd because if you call it directly, it stores all the relevant information about the current processor state (such as the contents of the instruction pointer and runtime stack pointer) in the <strong>jmp_buf</strong> and returns zero. In this case it behaves like an ordinary function. However, if you call <strong>longjmp( )</strong> using the same <strong>jmp_buf</strong>, it’s as if you’re returning from <strong>setjmp( )</strong> again—you pop right out the back end of the <strong>setjmp( )</strong>. This time, the value returned is the second argument to <strong>longjmp( )</strong>, so you can detect that you’re actually coming back from a <strong>longjmp( )</strong>. You can imagine that with many different <strong>jmp_buf</strong>s, you could pop around to many different places in the program. The difference between a local <strong>goto</strong> (with a label) and this nonlocal goto is that you can return to any pre-determined location higher up in the runtime stack with <strong>setjmp( )</strong>/<strong>longjmp( )</strong> (wherever you’ve placed a call to <strong>setjmp( )</strong>)<sup>.</sup></p><p>The problem in C++ is that <strong>longjmp( )</strong> doesn’t respect objects; in particular it doesn’t call destructors when it jumps out of a scope.<a l:href="#n1" type="note">[1]</a> Destructor calls are essential, so this approach won’t work with C++. In fact, the C++ standard states that branching into a scope with <strong>goto</strong> (effectively bypassing constructor calls), or branching out of a scope with <strong>longjmp( )</strong> where an object on the stack has a destructor, constitutes undefined behavior<sup>.</sup></p></section><section><title><p>Throwing an exception</p></title><p>If you encounter an exceptional situation in your code—that is, one in which you don’t have enough information in the current context to decide what to do—you can send information about the error into a larger context by creating an object that contains that information and "throwing" it out of your current context. This is called <emphasis>throwing an exception</emphasis>. Here’s what it looks like:<sup>.</sup></p><p><code>//: C01:MyError.cpp</code></p><p><code>class MyError {</code></p><p><code>   const char* const data;</code></p><p><code>public:</code></p><p><code>   MyError(const char* const msg = 0) : data (msg) {}</code></p><p><code>};</code></p><empty-line/><p><code>void f() {</code></p><p><code>   // Here we "throw" an exception object:</code></p><p><code>   throw MyError("something bad happened");</code></p><p><code>}</code></p><empty-line/><p><code>int main() {</code></p><p><code>   // As you’ll see shortly,</code></p><p><code>   // we’ll want a "try block" here:</code></p><p><code>   f();</code></p><p><code>} ///:~</code></p><empty-line/><p><strong>MyError</strong> is an ordinary class, which in this case takes a <strong>char*</strong> as a constructor argument. You can use any type when you throw (including built-in types), but usually you’ll create special classes for throwing exceptions<sup>.</sup></p><p>The keyword <strong>throw</strong> causes a number of relatively magical things to happen. First, it creates a copy of the object you’re throwing and, in effect, "returns" it from the function containing the throw expression, even though that object type isn’t normally what the function is designed to return. A naive way to think about exception handling is as an alternate return mechanism (although you find you can get into trouble if you take the analogy too far). You can also exit from ordinary scopes by throwing an exception. In any case, a value is returned, and the function or scope exits<sup>.</sup></p><p>Any similarity to function returns ends there because <emphasis>where</emphasis> you return is some place completely different from where a normal function call returns. (You end up in an appropriate part of the code—called an exception handler—that might be far removed from where the exception was thrown.) In addition, any local objects created by the time the exception occurs are destroyed. This automatic cleanup of local objects is often called "stack unwinding."<sup>.</sup></p><p>In addition, you can throw as many different types of objects as you want. Typically, you’ll throw a different type for each category of error. The idea is to store the information in the object and in the <emphasis>name</emphasis> of its class so that someone in a calling context can figure out what to do with your exception<sup>.</sup></p></section><section><title><p>Catching an exception</p></title><section><p>As mentioned earlier, one of the advantages of C++ exception handling is that it allows you to concentrate on the problem you’re actually trying to solve in one place, and then deal with the errors from that code in another place<sup>.</sup></p></section><section><title><p>The try block</p></title><p>If you’re inside a function and you throw an exception (or a called function throws an exception), the function exits in the process of throwing. If you don’t want a <strong>throw </strong>to leave a function, you can set up a special block within the function where you try to solve your actual programming problem (and potentially generate exceptions). This block is called the <emphasis>try block</emphasis> because you try your various function calls there. The try block is an ordinary scope, preceded by the keyword <strong>try</strong>:<sup>.</sup></p><p><code>try {</code></p><p><code>  // Code that may generate exceptions</code></p><p><code>}</code></p><empty-line/><p>If you check for errors by carefully examining the return codes from the functions you use, you need to surround every function call with setup and test code, even if you call the same function several times. With exception handling, you put everything in a <strong>try</strong> block and handle exceptions after the <strong>try</strong> block. Thus, your code is a lot easier to write and easier to read because the goal of the code is not confused with the error checking<sup>.</sup></p></section><section><title><p>Exception handlers</p></title><p>Of course, the thrown exception must end up some place. This place is the <emphasis>exception handler</emphasis>, and you need one exception handler for every exception type you want to catch. Exception handlers immediately follow the <strong>try</strong> block and are denoted by the keyword <strong>catch</strong>:<sup>.</sup></p><p><code>try {</code></p><p><code>  // Code that may generate exceptions</code></p><p><code>} catch(type1 id1) {</code></p><p><code>  // Handle exceptions of type1</code></p><p><code>} catch(type2 id2) {</code></p><p><code>  // Handle exceptions of type2</code></p><p><code>} catch(type3 id3)</code></p><p><code>  // Etc...</code></p><p><code>} catch(typeN idN)</code></p><p><code>  // Handle exceptions of typeN</code></p><p><code>}</code></p><p><code>// Normal execution resumes here...</code></p><empty-line/><p>The syntax of a <strong>catch</strong> clause resembles functions that take a single argument. The identifier (<strong>id1</strong>, <strong>id2</strong>, and so on) can be used inside the handler, just like a function argument, although you can omit the identifier if it’s not needed in the handler. The exception type usually gives you enough information to deal with it<sup>.</sup></p><p>The handlers must appear directly after the <strong>try</strong> block. If an exception is thrown, the exception-handling mechanism goes hunting for the first handler with an argument that matches the type of the exception. It then enters that <strong>catch</strong> clause, and the exception is considered handled. (The search for handlers stops once the <strong>catch</strong> clause is found.) Only the matching <strong>catch</strong> clause executes; control then resumes after the last handler associated with that try block<sup>.</sup></p><p>Notice that, within the <strong>try</strong> block, a number of different function calls might generate the same type of exception, but you need only one handler<sup>.</sup></p><p>To illustrate using <strong>try</strong> and <strong>catch</strong>, the following variation of <strong>Nonlocal.cpp</strong> replaces the call to <strong>setjmp( )</strong> with a <strong>try</strong> block and replaces the call to <strong>longjmp( )</strong> with a <strong>throw</strong> statement<sup>.</sup></p><p><code>//: C01:Nonlocal2.cpp</code></p><p><code>// Illustrates exceptions</code></p><p><code>#include &lt;iostream&gt;</code></p><p><code>using namespace std;</code></p><empty-line/><p><code>class Rainbow {</code></p><p><code>public:</code></p><p><code>  Rainbow() { cout &lt;&lt; "Rainbow()" &lt;&lt; endl; }</code></p><p><code>  ~Rainbow() { cout &lt;&lt; "~Rainbow()" &lt;&lt; endl; }</code></p><p><code>};</code></p><empty-line/><p><code>void oz() {</code></p><p><code>  Rainbow rb;</code></p><p><code>  for(int i = 0; i &lt; 3; i++)</code></p><p><code>    cout &lt;&lt; "there's no place like home\n";</code></p><p><code>  throw 47;</code></p><p><code>}</code></p><empty-line/><p><code>int main() {</code></p><p><code>  try {</code></p><p><code>    cout &lt;&lt; "tornado, witch, munchkins...\n";</code></p><p><code>    oz();</code></p><p><code>  }</code></p><p><code>  catch (int) {</code></p><p><code>    cout &lt;&lt; "Auntie Em! "</code></p><p><code>         &lt;&lt; "I had the strangest dream..."</code></p><p><code>         &lt;&lt; endl;</code></p><p><code>  }</code></p><p><code>} ///:~</code></p><empty-line/><p>When the <strong>throw</strong> statement in <strong>oz( )</strong> executes, program control backtracks until it finds the <strong>catch</strong> clause that takes an <strong>int</strong> parameter, at which point execution resumes with the body of that <strong>catch</strong> clause. The most important difference between this program and <strong>Nonlocal.cpp</strong> is that the destructor for the object <strong>rb</strong> is called when the <strong>throw</strong> statement causes execution to leave the function <strong>oz( )</strong><sup><strong>.</strong></sup></p><p>There are two basic models in exception-handling theory: termination and resumption. In <emphasis>termination</emphasis> (which is what C++ supports), you assume the error is so critical that there’s no way to automatically resume execution at the point where the exception occurred. In other words, "whoever" threw the exception decided there was no way to salvage the situation, and they don’t <emphasis>want</emphasis> to come back<sup>.</sup></p><p>The alternative error-handling model is called <emphasis>resumption</emphasis>, first introduced with the PL/I language in the 1960s<a l:href="#n2" type="note">[2]</a>.Using resumption semantics means that the exception handler is expected to do something to rectify the situation, and then the faulting code is automatically retried, presuming success the second time. If you want resumption in C++, you must explicitly transfer execution back to the code where the error occurred, usually by repeating the function call that sent you there in the first place. It is not unusual, therefore, to place your <strong>try</strong> block inside a <strong>while</strong> loop that keeps reentering the <strong>try</strong> block until the result is satisfactory<sup>.</sup></p><p>Historically, programmers using operating systems that supported resumptive exception handling eventually ended up using termination-like code and skipping resumption. Although resumption sounds attractive at first, it seems it isn’t quite so useful in practice. One reason may be the distance that can occur between the exception and its handler; it is one thing to terminate to a handler that’s far away, but to jump to that handler and then back again may be too conceptually difficult for large systems on which the exception can be generated from many points<sup>.</sup></p></section></section><section><title><p>Exception matching</p></title><section><p>When an exception is thrown, the exception-handling system looks through the "nearest" handlers in the order they appear in the source code. When it finds a match, the exception is considered handled and no further searching occurs<sup>.</sup></p><p>Matching an exception doesn’t require a perfect correlation between the exception and its handler. An object or reference to a derived-class object will match a handler for the base class. (However, if the handler is for an object rather than a reference, the exception object is "sliced"— truncated to the base type — as it is passed to the handler; this does no damage but loses all the derived-type information.) For this reason, as well as to avoid making yet another copy of the exception object, it is always better to catch an exception by <emphasis>reference</emphasis> instead of by value<a l:href="#n3" type="note">[3]</a>. If a pointer is thrown, the usual standard pointer conversions are used to match the exception. However, no automatic type conversions are used to convert from one exception type to another in the process of matching, for example:<sup>.</sup></p><p>//: C01:Autoexcp.cpp</p><p>// No matching conversions</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Except1 {};</p><p>class Except2 {</p><p>public:</p><p>  Except2(const Except1&amp;) {}</p><p>};</p><empty-line/><p>void f() { throw Except1(); }</p><empty-line/><p>int main() {</p><p>  try { f();</p><p>  } catch (Except2&amp;) {</p><p>    cout &lt;&lt; "inside catch(Except2)" &lt;&lt; endl;</p><p>  } catch (Except1&amp;) {</p><p>    cout &lt;&lt; "inside catch(Except1)" &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>Even though you might think the first handler could be used by converting an <strong>Except1</strong> object into an <strong>Except2</strong> using the constructor conversion, the system will not perform such a conversion during exception handling, and you’ll end up at the <strong>Except1</strong> handler<sup>.</sup></p><p>The following example shows how a base-class handler can catch a derived-class exception:<sup>.</sup></p><p><code>//: C01:Basexcpt.cpp</code></p><p><code>// Exception hierarchies</code></p><p><code>#include &lt;iostream&gt;</code></p><p><code>using namespace std;</code></p><empty-line/><p><code>class X {</code></p><p><code>public:</code></p><p><code>  class Trouble {};</code></p><p><code>  class Small : public Trouble {};</code></p><p><code>  class Big : public Trouble {};</code></p><p><code>  void f() { throw Big(); }</code></p><p><code>};</code></p><empty-line/><p><code>int main() {</code></p><p><code>  X x;</code></p><p><code>  try {</code></p><p><code>    x.f();</code></p><p><code>  } catch(X::Trouble&amp;) {</code></p><p><code>    cout &lt;&lt; "caught Trouble" &lt;&lt; endl;</code></p><p><code>  // Hidden by previous handler:</code></p><p><code>  } catch(X::Small&amp;) {</code></p><p><code>    cout &lt;&lt; "caught Small Trouble" &lt;&lt; endl;</code></p><p><code>  } catch(X::Big&amp;) {</code></p><p><code>    cout &lt;&lt; "caught Big Trouble" &lt;&lt; endl;</code></p><p><code>  }</code></p><p><code>} ///:~</code></p><empty-line/><p>Here, the exception-handling mechanism will always match a <strong>Trouble</strong> object, <emphasis>or anything that is a</emphasis><strong>Trouble</strong> (through public inheritance),<a l:href="#n4" type="note">[4]</a> to the first handler. That means the second and third handlers are never called because the first one captures them all. It makes more sense to catch the derived types first and put the base type at the end to catch anything less specific<sup>.</sup></p><p>Notice that these examples catch exceptions by reference, although for these classes it isn’t important because there are no additional members in the derived classes, and there are no argument identifiers in the handlers anyway. You’ll usually want to use reference arguments rather than value arguments in your handlers to avoid slicing off information<sup>.</sup></p></section><section><title><p>Catching any exception</p></title><p>Sometimes you want to create a handler that catches <emphasis>any</emphasis> type of exception. You do this using the ellipsis in the argument list:<sup>.</sup></p><p>Catch(...) {</p><p>  cout &lt;&lt; "an exception was thrown" &lt;&lt; endl;</p><p>}</p><empty-line/><p>An ellipsis catches any exception, so you’ll want to put it at the <emphasis>end</emphasis> of your list of handlers to avoid pre-empting any that follow it<sup>.</sup></p><p>Because the ellipsis gives you no possibility to have an argument, you can’t know anything about the exception or its type. It’s a "catchall." Such a <strong>catch</strong> clause is often used to clean up some resources and then rethrow the exception<sup>.</sup></p></section><section><title><p>Re-throwing an exception</p></title><p>You usually want to re-throw an exception when you have some resource that needs to be released, such as a network connection or heap memory that needs to be deallocated. (See the section "Resource Management" later in this chapter for more detail). If an exception occurs, you don’t necessarily care what error caused the exception—you just want to close the connection you opened previously. After that, you’ll want to let some other context closer to the user (that is, higher up in the call chain) handle the exception. In this case the ellipsis specification is just what you want. You want to catch <emphasis>any</emphasis> exception, clean up your resource, and then re-throw the exception so that it can be handled elsewhere. You re-throw an exception by using <strong>throw</strong> with no argument inside a handler:<sup>.</sup></p><p><code>catch(...) {</code></p><p><code>cout &lt;&lt; "an exception was thrown" &lt;&lt; endl;</code></p><p><code>// Deallocate your resource here, and then re-throw…</code></p><p><code>  throw;</code></p><p><code>}</code></p><empty-line/><p>Any further <strong>catch</strong> clauses for the same <strong>try</strong> block are still ignored—the <strong>throw</strong> causes the exception to go to the exception handlers in the next-higher context. In addition, everything about the exception object is preserved, so the handler at the higher context that catches the specific exception type can extract any information the object may contain<sup>.</sup></p></section><section><title><p>Uncaught exceptions</p></title><section><p>As we explained in the beginning of this chapter, exception handling is considered better than the traditional return-an-error-code technique because exceptions can’t be ignored. If none of the exception handlers following a particular <strong>try</strong> block matches an exception, that exception moves to the next-higher context, that is, the function or <strong>try</strong> block surrounding the <strong>try</strong> block that did not catch the exception. (The location of this <strong>try</strong> block is not always obvious at first glance, since it’s higher up in the call chain.) This process continues until, at some level, a handler matches the exception. At that point, the exception is considered "caught," and no further searching occurs<sup>.</sup></p></section><section><section><title><p>The terminate( ) function</p></title><p>If no handler at any level catches the exception, the special library function <strong>terminate( )</strong> (declared in the <strong>&lt;exception&gt;</strong> header) is automatically called. By default, <strong>terminate( )</strong> calls the Standard C library function <strong>abort( )</strong>, which abruptly exits the program. On Unix systems, <strong>abort( )</strong> also causes a core dump. When <strong>abort( )</strong> is called, no calls to normal program termination functions occur, which means that destructors for global and static objects do not execute. The <strong>terminate( )</strong> function also executes if a destructor for a local object throws an exception during stack unwinding (interrupting the exception that was in progress) or if a global or static object’s constructor or destructor throws an exception. In general, do not allow a destructor to throw an exception<sup>.</sup></p></section><section><title><p>The set_terminate( ) function</p></title><p>You can install your own <strong>terminate( )</strong> function using the standard <strong>set_terminate( )</strong> function, which returns a pointer to the <strong>terminate( )</strong> function you are replacing (which will be the default library version the first time you call it), so you can restore it later if you want. Your custom <strong>terminate( )</strong> must take no arguments and have a <strong>void</strong> return value. In addition, any <strong>terminate( )</strong> handler you install must not return or throw an exception, but instead must execute some sort of program-termination logic. If <strong>terminate( )</strong> is called, the problem is unrecoverable<sup>.</sup></p><p>The following example shows the use of <strong>set_terminate( )</strong>. Here, the return value is saved and restored so that the <strong>terminate( )</strong> function can be used to help isolate the section of code in which the uncaught exception is occurring:<sup>.</sup></p><p><code>//: C01:Terminator.cpp</code></p><p><code>// Use of set_terminate()</code></p><p><code>// Also shows uncaught exceptions</code></p><p><code>#include &lt;exception&gt;</code></p><p><code>#include &lt;iostream&gt;</code></p><p><code>#include &lt;cstdlib&gt;</code></p><p><code>using namespace std;</code></p><empty-line/><p><code>void terminator() {</code></p><p><code>  cout &lt;&lt; "I'll be back!" &lt;&lt; endl;</code></p><p><code>  exit(0);</code></p><p><code>}</code></p><empty-line/><p><code>void (*old_terminate)()</code></p><p><code>  = set_terminate(terminator);</code></p><empty-line/><p><code>class Botch {</code></p><p><code>public:</code></p><p><code>  class Fruit {};</code></p><p><code>  void f() {</code></p><p><code>    cout &lt;&lt; "Botch::f()" &lt;&lt; endl;</code></p><p><code>    throw Fruit();</code></p><p><code>  }</code></p><p><code>  ~Botch() { throw 'c'; }</code></p><p><code>};</code></p><empty-line/><p><code>int main() {</code></p><p><code>  try {</code></p><p><code>    Botch b;</code></p><p><code>    b.f();</code></p><p><code>  } catch(...) {</code></p><p><code>    cout &lt;&lt; "inside catch(...)" &lt;&lt; endl;</code></p><p><code>  }</code></p><p><code>} ///:~</code></p><empty-line/><p>The definition of <strong>old_terminate</strong> looks a bit confusing at first: it not only creates a pointer to a function, but it initializes that pointer to the return value of <strong>set_terminate( )</strong>. Even though you might be familiar with seeing a semicolon right after a pointer-to-function declaration, here it’s just another kind of variable and can be initialized when it is defined<sup>.</sup></p><p>The class <strong>Botch</strong> not only throws an exception inside <strong>f( )</strong>, but also in its destructor. As we explained earlier, this situation causes a call to <strong>terminate( )</strong>, as you can see in <strong>main( )</strong>. Even though the exception handler says <strong>catch(...)</strong>, which would seem to catch everything and leave no cause for <strong>terminate( )</strong> to be called, <strong>terminate( ) </strong>is called anyway. In the process of cleaning up the objects on the stack to handle one exception, the <strong>Botch</strong> destructor is called, and that generates a second exception, forcing a call to <strong>terminate( )</strong>. Thus, a destructor that throws an exception or causes one to be thrown is usually a sign of poor design or sloppy coding<sup>.</sup></p></section></section></section></section><section><title><p>Cleaning up</p></title><section><p>Part of the magic of exception handling is that you can pop from normal program flow into the appropriate exception handler. Doing so wouldn’t be useful, however, if things weren’t cleaned up properly as the exception was thrown. C++ exception handling guarantees that as you leave a scope, all objects in that scope <emphasis>whose constructors have been completed</emphasis> will have destructors called<sup>.</sup></p><p>Here’s an example that demonstrates that constructors that aren’t completed don’t have the associated destructors called. It also shows what happens when an exception is thrown in the middle of the creation of an array of objects:<sup>.</sup></p><p><code>//: C01:Cleanup.cpp</code></p><p><code>// Exceptions clean up complete objects only</code></p><p><code>#include &lt;iostream&gt;</code></p><p><code>using namespace std;</code></p><empty-line/><p><code>class Trace {</code></p><p><code>  static int counter;</code></p><p><code>  int objid;</code></p><p><code>public:</code></p><p><code>  Trace() {</code></p><p><code>    objid = counter++;</code></p><p><code>    cout &lt;&lt; "constructing Trace #" &lt;&lt; objid &lt;&lt; endl;</code></p><p><code>    if(objid == 3) throw 3;</code></p><p><code>  }</code></p><p><code>  ~Trace() {</code></p><p><code>    cout &lt;&lt; "destructing Trace #" &lt;&lt; objid &lt;&lt; endl;</code></p><p><code>  }</code></p><p><code>};</code></p><empty-line/><p><code>int Trace::counter = 0;</code></p><empty-line/><p><code>int main() {</code></p><p><code>  try {</code></p><p><code>    Trace n1;</code></p><p><code>    // Throws exception:</code></p><p><code>    Trace array[5];</code></p><p><code>    Trace n2;  // won't get here</code></p><p><code>  } catch(int i) {</code></p><p><code>    cout &lt;&lt; "caught " &lt;&lt; i &lt;&lt; endl;</code></p><p><code>  }</code></p><p><code>} ///:~</code></p><empty-line/><p>The class <strong>Trace</strong> keeps track of objects so that you can trace program progress. It keeps a count of the number of objects created with a <strong>static</strong> data member <strong>counter</strong> and tracks the number of the particular object with <strong>objid</strong><sup><strong>.</strong></sup></p><p>The main program creates a single object, <strong>n1</strong> (<strong>objid</strong> 0), and then attempts to create an array of five <strong>Trace</strong> objects, but an exception is thrown before the third object is fully created. The object <strong>n2</strong> is never created. You can see the results in the output of the program:<sup>.</sup></p><p><code>constructing Trace #0</code></p><p><code>constructing Trace #1</code></p><p><code>constructing Trace #2</code></p><p><code>constructing Trace #3</code></p><p><code>destructing Trace #2</code></p><p><code>destructing Trace #1</code></p><p><code>destructing Trace #0</code></p><p><code>caught 3</code></p><empty-line/><p>Three array elements are successfully created, but in the middle of the constructor for the fourth element, an exception is thrown. Because the fourth construction in <strong>main( )</strong> (for <strong>array[2]</strong>) never completes, only the destructors for objects <strong>array[1]</strong> and <strong>array[0]</strong> are called. Finally, object <strong>n1</strong> is destroyed, but not object <strong>n2</strong>, because it was never created<sup>.</sup></p></section><section><title><p>Resource management</p></title><p>When writing code with exceptions, it’s particularly important that you always ask, "If an exception occurs, will my resources be properly cleaned up?" Most of the time you’re fairly safe, but in constructors there’s a particular problem: if an exception is thrown before a constructor is completed, the associated destructor will not be called for that object. Thus, you must be especially diligent while writing your constructor<sup>.</sup></p><p>The general difficulty is allocating resources in constructors. If an exception occurs in the constructor, the destructor doesn’t get a chance to deallocate the resource. This problem occurs most often with "naked" pointers. For example:<sup>.</sup></p><p>//: C01:Rawp.cpp</p><p>// Naked pointers</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Cat {</p><p>public:</p><p>  Cat() { cout &lt;&lt; "Cat()" &lt;&lt; endl; }</p><p>  ~Cat() { cout &lt;&lt; "~Cat()" &lt;&lt; endl; }</p><p>};</p><empty-line/><p>class Dog {</p><p>public:</p><p>  void* operator new(size_t sz) {</p><p>    cout &lt;&lt; "allocating a Dog" &lt;&lt; endl;</p><p>    throw 47;</p><p>  }</p><p>  void operator delete(void* p) {</p><p>    cout &lt;&lt; "deallocating a Dog" &lt;&lt; endl;</p><p>    ::operator delete(p);</p><p>  }</p><p>};</p><empty-line/><p>class UseResources {</p><p>  Cat* bp;</p><p>  Dog* op;</p><p>public:</p><p>  UseResources(int count = 1) {</p><p>    cout &lt;&lt; "UseResources()" &lt;&lt; endl;</p><p>    bp = new Cat[count];</p><p>    op = new Dog;</p><p>  }</p><p>  ~UseResources() {</p><p>    cout &lt;&lt; "~UseResources()" &lt;&lt; endl;</p><p>    delete [] bp; // Array delete</p><p>    delete op;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  try {</p><p>    UseResources ur(3);</p><p>  } catch(int) {</p><p>    cout &lt;&lt; "inside handler" &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>The output is the following:<sup>.</sup></p><p>UseResources()</p><p>Cat()</p><p>Cat()</p><p>Cat()</p><p>allocating a Dog</p><p>inside handler</p><empty-line/><p>The <strong>UseResources</strong> constructor is entered, and the <strong>Cat</strong> constructor is successfully completed for the three array objects. However, inside <strong>Dog::operator new( )</strong>, an exception is thrown (to simulate an out-of-memory error). Suddenly, you end up inside the handler, <emphasis>without</emphasis> the <strong>UseResources</strong> destructor being called. This is correct because the <strong>UseResources</strong> constructor was unable to finish, but it also means the <strong>Cat</strong> objects that were successfully created on the heap were never destroyed<sup>.</sup></p></section><section><title><p>Making everything an object</p></title><p>To prevent such resource leaks, you must guard against these "raw" resource allocations in one of two ways:</p><p>·         You can catch exceptions inside the constructor and then release the resource.</p><p>·         You can place the allocations inside an object’s constructor, and you can place the deallocations inside an object’s destructor.</p><p>Using the latter approach, each allocation becomes atomic, by virtue of being part of the lifetime of a local object, and if it fails, the other resource allocation objects are properly cleaned up during stack unwinding. This technique is called Resource Acquisition Is Initialization (RAII for short) , because it equates resource control with object lifetime. Using templates is an excellent way to modify the previous example to achieve this:<sup>.</sup></p><p>//: C01:Wrapped.cpp</p><p>// Safe, atomic pointers</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>// Simplified. Yours may have other arguments.</p><p>template&lt;class T, int sz = 1&gt; class PWrap {</p><p>  T* ptr;</p><p>public:</p><p>  class RangeError {}; // Exception class</p><p>  PWrap() {</p><p>    ptr = new T[sz];</p><p>    cout &lt;&lt; "PWrap constructor" &lt;&lt; endl;</p><p>  }</p><p>  ~PWrap() {</p><p>    delete [] ptr;</p><p>    cout &lt;&lt; "PWrap destructor" &lt;&lt; endl;</p><p>  }</p><p>  T&amp; operator[](int i) throw(RangeError) {</p><p>    if(i &gt;= 0 &amp;&amp; i &lt; sz) return ptr[i];</p><p>    throw RangeError();</p><p>  }</p><p>};</p><empty-line/><p>class Cat {</p><p>public:</p><p>  Cat() { cout &lt;&lt; "Cat()" &lt;&lt; endl; }</p><p>  ~Cat() { cout &lt;&lt; "~Cat()" &lt;&lt; endl; }</p><p>  void g() {}</p><p>};</p><empty-line/><p>class Dog {</p><p>public:</p><p>  void* operator new[](size_t) {</p><p>    cout &lt;&lt; "Allocating a Dog" &lt;&lt; endl;</p><p>    throw 47;</p><p>  }</p><p>  void operator delete[](void* p) {</p><p>    cout &lt;&lt; "Deallocating a Dog" &lt;&lt; endl;</p><p>    ::operator delete[](p);</p><p>  }</p><p>};</p><empty-line/><p>class UseResources {</p><p>  PWrap&lt;Cat, 3&gt; cats;</p><p>  PWrap&lt;Dog&gt; dog;</p><p>public:</p><p>  UseResources() {</p><p>    cout &lt;&lt; "UseResources()" &lt;&lt; endl;</p><p>  }</p><p>  ~UseResources() {</p><p>    cout &lt;&lt; "~UseResources()" &lt;&lt; endl;</p><p>  }</p><p>  void f() { cats[1].g(); }</p><p>};</p><empty-line/><p>int main() {</p><p>  try {</p><p>    UseResources ur;</p><p>  } catch(int) {</p><p>    cout &lt;&lt; "inside handler" &lt;&lt; endl;</p><p>  } catch(...) {</p><p>    cout &lt;&lt; "inside catch(...)" &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>The difference is the use of the template to wrap the pointers and make them into objects. The constructors for these objects are called <emphasis>before</emphasis> the body of the <strong>UseResources</strong> constructor, and any of these constructors that complete before an exception is thrown will have their associated destructors called during stack unwinding<sup>.</sup></p><p>The <strong>PWrap</strong> template shows a more typical use of exceptions than you’ve seen so far: A nested class called <strong>RangeError</strong> is created to use in <strong>operator[ ]</strong> if its argument is out of range. Because <strong>operator[ ]</strong> returns a reference, it cannot return zero. (There are no null references.) This is a true exceptional condition—you don’t know what to do in the current context, and you can’t return an improbable value. In this example, <strong>RangeError</strong> is simple and assumes all the necessary information is in the class name, but you might also want to add a member that contains the value of the index, if that is useful<sup>.</sup></p><p>Now the output is:<sup>.</sup></p><p>Cat()</p><p>Cat()</p><p>Cat()</p><p>PWrap constructor</p><p>allocating a Dog</p><p>~Cat()</p><p>~Cat()</p><p>~Cat()</p><p>PWrap destructor</p><p>inside handler</p><empty-line/><p>Again, the storage allocation for <strong>Dog</strong> throws an exception, but this time the array of <strong>Cat</strong> objects is properly cleaned up, so there is no memory leak<sup>.</sup></p></section><section><title><p>auto_ptr</p></title><p>Since dynamic memory is the most frequent resource used in a typical C++ program, the standard provides an RAII wrapper for pointers to heap memory that automatically frees the memory. The <strong>auto_ptr</strong> class template, defined in the <strong>&lt;memory&gt;</strong> header, has a constructor that takes a pointer to its generic type (whatever you use in your code). The <strong>auto_ptr</strong> class template also overloads the pointer operators <strong>*</strong> and <strong>-&gt;</strong> to forward these operations to the original pointer the <strong>auto_ptr</strong> object is holding. You can, therefore, use the <strong>auto_ptr</strong> object as if it were a raw pointer. Here’s how it works:<sup>.</sup></p><p>//: C01:Auto_ptr.cpp</p><p>// Illustrates the RAII nature of auto_ptr</p><p>#include &lt;memory&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class TraceHeap {</p><p>  int i;</p><p>public:</p><p>  static void* operator new(size_t siz) {</p><p>    void* p = ::operator new(siz);</p><p>    cout &lt;&lt; "Allocating TraceHeap object on the heap "</p><p>         &lt;&lt; "at address " &lt;&lt; p &lt;&lt; endl;</p><p>    return p;</p><p>  }</p><p>  static void operator delete(void* p) {</p><p>    cout &lt;&lt; "Deleting TraceHeap object at address "</p><p>         &lt;&lt; p &lt;&lt; endl;</p><p>    ::operator delete(p);</p><p>  }</p><p>  TraceHeap(int i) : i(i) {}</p><p>  int getVal() const {</p><p>    return i;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  auto_ptr&lt;TraceHeap&gt; pMyObject(new TraceHeap(5));</p><p>  cout &lt;&lt; pMyObject-&gt;getVal() &lt;&lt; endl;  // prints 5</p><p>} ///:~</p><empty-line/><p>The <strong>TraceHeap</strong> class overloads the <strong>operator new</strong> and <strong>operator delete</strong> so you can see exactly what’s happening. Notice that, like any other class template, you specify the type you’re going to use in a template parameter. You don’t say <strong>TraceHeap*</strong>, however; <strong>auto_ptr</strong> already knows that it will be storing a pointer to your type. The second line of <strong>main( )</strong> verifies that <strong>auto_ptr</strong>’s <strong>operator-&gt;( )</strong> function applies the indirection to the original, underlying pointer. Most important, even though we didn’t explicitly delete the original pointer (in fact we can’t here, since we didn’t save its address in a variable anywhere), <strong>pMyObject</strong>’s destructor deletes the original pointer during stack unwinding, as the following output verifies:<sup>.</sup></p><p>Allocating TraceHeap object on the heap at address 8930040</p><p>5</p><p>Deleting TraceHeap object at address 8930040</p><empty-line/><p><strong>The auto_ptr</strong> class template is also handy for pointer data members. Since class objects contained by value are always destructed, <strong>auto_ptr</strong> members always delete the raw pointer they wrap when the containing object is destructed<a l:href="#n5" type="note">[5]</a>.</p></section><section><title><p>Function-level try blocks</p></title><p>Since constructors can routinely throw exceptions, you might want to handle exceptions that occur when an object’s member or base subobjects are initialized. To do this, you can place the initialization of such subobjects in a <emphasis>function-level try block</emphasis>. In a departure from the usual syntax, the <strong>try</strong> block for constructor initializers is the constructor body, and the associated <strong>catch</strong> block follows the body of the constructor, as in the following example<sup>.</sup></p><p>//: C01:InitExcept.cpp</p><p>// Handles exceptions from subobjects</p><p>//{-bor}</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Base {</p><p>  int i;</p><p>public:</p><p>  class BaseExcept {};</p><p>  Base(int i) : i(i) {</p><p>    throw BaseExcept();</p><p>  }</p><p>};</p><empty-line/><p>class Derived : public Base {</p><p>public:</p><p>  class DerivedExcept {</p><p>    const char* msg;</p><p>  public:</p><p>    DerivedExcept(const char* msg) : msg(msg) {}</p><p>    const char* what() const {</p><p>      return msg;</p><p>    }</p><p>  };</p><p>  Derived(int j)</p><p>  try</p><p>    : Base(j) {</p><p>    // Constructor body</p><p>    cout &lt;&lt; "This won't print\n";</p><p>  }</p><p>  catch (BaseExcept&amp;) {</p><p>    throw DerivedExcept("Base subobject threw");;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  try {</p><p>    Derived d(3);</p><p>  }</p><p>  catch (Derived::DerivedExcept&amp; d) {</p><p>    cout &lt;&lt; d.what() &lt;&lt; endl;  // "Base subobject threw"</p><p>  }</p><p>} ///:~</p><empty-line/><p>Notice that the initializer list in the constructor for <strong>Derived</strong> goes after the <strong>try</strong> keyword but before the constructor body. If an exception does indeed occur, the contained object is not constructed, so it makes no sense to return to the code that created it. For this reason, the only sensible thing to do is to throw an exception in the function-level <strong>catch</strong> clause<sup>.</sup></p><p>Although it is not terribly useful, C++ also allows function-level <strong>try</strong> blocks for <emphasis>any</emphasis> function, as the following example illustrates:</p><p>//: C01:FunctionTryBlock.cpp</p><p>// Function-level try blocks</p><p>//{-bor}</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>int main() try {</p><p>  throw "main";</p><p>} catch(const char* msg) {</p><p>cout &lt;&lt; msg &lt;&lt; endl;</p><p>return 1;</p><p>} ///:~</p><empty-line/><p>In this case, the <strong>catch</strong> block can return in the same manner that the function body normally returns. Using this type of function-level <strong>try</strong> block isn’t much different from inserting a <strong>try-catch</strong> around the code inside of the function body<sup>.</sup></p></section></section><section><title><p>Standard exceptions</p></title><p>The set of exceptions used with the Standard C++ library is also available for your use. Generally it’s easier and faster to start with a standard exception class than to try to define your own. If the standard class doesn’t do exactly what you need, you can derive from it<sup>.</sup></p><p>All standard exception classes derive ultimately from the class <strong>exception</strong>, defined in the header <strong>&lt;exception&gt;</strong>. The two main derived classes are <strong>logic_error</strong> and <strong>runtime_error</strong>, which are found in <strong>&lt;stdexcept&gt;</strong> (which itself includes <strong>&lt;exception&gt;</strong>). The class <strong>logic_error</strong> represents errors in programming logic, such as passing an invalid argument. Runtime errors are those that occur as the result of unforeseen forces such as hardware failure or memory exhaustion. Both <strong>runtime_error</strong> and <strong>logic_error</strong> provide a constructor that takes a <strong>std::string</strong> argument so that you can store a message in the exception object and extract it later with <strong>exception::what( )</strong> , as the following program illustrates<sup>.</sup></p><p>//: C01:StdExcept.cpp</p><p>// Derives an exception class from std::runtime_error</p><p>#include &lt;stdexcept&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class MyError : public runtime_error {</p><p>public:</p><p>  MyError(const string&amp; msg = "") : runtime_error(msg) {}</p><p>};</p><empty-line/><p>int main() {</p><p>  try {</p><p>    throw MyError("my message");</p><p>  }</p><p>  catch (MyError&amp; x) {</p><p>    cout &lt;&lt; x.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>Although the <strong>runtime_error</strong> constructor passes the message up to its <strong>std::exception</strong> subobject to hold, <strong>std::exception</strong> does not provide a constructor that takes a <strong>std::string</strong> argument. Therefore, you usually want to derive your exception classes from either <strong>runtime_error</strong> or <strong>logic_error</strong> (or one of their derivatives), and not from <strong>std::exception</strong><sup><strong>.</strong></sup></p><p>The following tables describe the standard exception classes.</p><table><tr align="left"><td align="left" valign="top"><strong>exception</strong></td><td align="left" valign="top">The base class for all the exceptions thrown by the C++ standard library. You can ask <strong>what( )</strong> and retrieve the optional string with which the exception was initialized.</td></tr><tr align="left"><td align="left" valign="top"><strong>logic_error</strong></td><td align="left" valign="top">Derived from <strong>exception</strong>. Reports program logic errors, which could presumably be detected by inspection.</td></tr><tr align="left"><td align="left" valign="top"><strong>runtime_error</strong></td><td align="left" valign="top">Derived from <strong>exception</strong>. Reports runtime errors, which can presumably be detected only when the program executes.</td></tr></table><empty-line/><p>The iostream exception class <strong>ios::failure</strong> is also derived from <strong>exception</strong>, but it has no further subclasses<sup>.</sup></p><p>You can use the classes in both of the following tables as they are, or you can use them as base classes from which to derive your own more specific types of exceptions<sup>.</sup></p><table><tr align="left"><th colspan="2" align="left" valign="top">Exception classes derived from logic_error</th></tr><tr align="left"><td align="left" valign="top"><strong>domain_error</strong></td><td align="left" valign="top">Reports violations of a precondition.</td></tr><tr align="left"><td align="left" valign="top"><strong>invalid_argument</strong></td><td align="left" valign="top">Indicates an invalid argument to the function from which it’s thrown.</td></tr><tr align="left"><td align="left" valign="top"><strong>length_error</strong></td><td align="left" valign="top">Indicates an attempt to produce an object whose length is greater than or equal to <strong>npos</strong> (the largest representable value of type <strong>size_t</strong>).</td></tr><tr align="left"><td align="left" valign="top"><strong>Out_of_range</strong></td><td align="left" valign="top">Reports an out-of-range argument.</td></tr><tr align="left"><td align="left" valign="top"><strong>Bad_cast</strong></td><td align="left" valign="top">Thrown for executing an invalid <strong>dynamic_cast</strong> expression in runtime type identification (see Chapter 8).</td></tr><tr align="left"><td align="left" valign="top"><strong>bad_typeid</strong></td><td align="left" valign="top">Reports a null pointer <strong>p</strong> in an expression <strong>typeid(*p)</strong>. (Again, a runtime type identification feature in Chapter 8).</td></tr></table><empty-line/><table><tr align="left"><th colspan="2" align="left" valign="top">Exception classes derived from runtime_error</th></tr><tr align="left"><td align="left" valign="top"><strong>range_error</strong></td><td align="left" valign="top">Reports violation of a postcondition.</td></tr><tr align="left"><td align="left" valign="top"><strong>overflow_error</strong></td><td align="left" valign="top">Reports an arithmetic overflow.</td></tr><tr align="left"><td align="left" valign="top"><strong>bad_alloc</strong></td><td align="left" valign="top">Reports a failure to allocate storage.</td></tr></table></section><section><title><p>Exception specifications</p></title><section><p>You’re not required to inform the people using your function what exceptions you might throw. Failure to do so can be considered uncivilized, however, because it means that users cannot be sure what code to write to catch all potential exceptions. Of course, if they have your source code, they can hunt through and look for <strong>throw</strong> statements, but often a library doesn’t come with sources. Good documentation can help alleviate this problem, but how many software projects are well documented? C++ provides syntax that allows you to tell the user what exceptions this function throws, so the user can handle them. This is the optional <emphasis>exception specification</emphasis>, which adorns a function’s declaration, appearing after the argument list<sup>.</sup></p><p>The exception specification reuses the keyword <strong>throw</strong>, followed by a parenthesized list of all the types of potential exceptions that the function can throw. Your function declaration might look like this:<sup>.</sup></p><p>void f() throw(toobig, toosmall, divzero);</p><empty-line/><p>As far as exceptions are concerned, the traditional function declaration</p><p>void f();</p><empty-line/><p>means that <emphasis>any</emphasis> type of exception can be thrown from the function. If you say</p><p>void f() throw();</p><empty-line/><p><emphasis>no exceptions whatsoever</emphasis> will be thrown from the function (so you’d better be sure that no functions farther down in the call chain let any exceptions propagate up!).</p><p>For good coding policy, good documentation, and ease-of-use for the function caller, always consider using exception specifications when you write functions that throw exceptions. (Exceptions to this guideline are discussed later in this chapter.)</p></section><section><section><section><title><p>The unexpected( ) function</p></title><p>If your exception specification claims you’re going to throw a certain set of exceptions and then you throw something that isn’t in that set, what’s the penalty? The special function <strong>unexpected( )</strong> is called when you throw something other than what appears in the exception specification. Should this unfortunate situation occur, the default implementation of <strong>unexpected</strong> calls the <strong>terminate( )</strong> function mentioned earlier in this chapter<sup>.</sup></p></section><section><title><p>The set_unexpected( ) function</p></title><p>Like <strong>terminate( )</strong>, the <strong>unexpected( )</strong> mechanism allows you to install your own function to respond to unexpected exceptions. You do so with a function called <strong>set_unexpected( ),</strong> which, like <strong>set_terminate( )</strong>, takes the address of a function with no arguments and <strong>void</strong> return value. Also, because it returns the previous value of the <strong>unexpected( )</strong> pointer, you can save it and restore it later. To use <strong>set_unexpected( )</strong>, include the header file <strong>&lt;exception&gt;</strong>. Here’s an example that shows a simple use of the features discussed so far in this section:<sup>.</sup></p><p>//: C01:Unexpected.cpp</p><p>// Exception specifications &amp; unexpected()</p><p>//{-msc} Doesn’t terminate properly</p><p>#include &lt;exception&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;cstdlib&gt;</p><p>using namespace std;</p><empty-line/><p>class Up {};</p><p>class Fit {};</p><p>void g();</p><empty-line/><p>void f(int i) throw (Up, Fit) {</p><p>  switch(i) {</p><p>    case 1: throw Up();</p><p>    case 2: throw Fit();</p><p>  }</p><p>  g();</p><p>}</p><empty-line/><p>// void g() {} // Version 1</p><p>void g() { throw 47; } // Version 2</p><empty-line/><p>void my_unexpected() {</p><p>  cout &lt;&lt; "unexpected exception thrown" &lt;&lt; endl;</p><p>  exit(0);</p><p>}</p><empty-line/><p>int main() {</p><p>  set_unexpected(my_unexpected);</p><p>  // (ignores return value)</p><p>  for(int i = 1; i &lt;=3; i++)</p><p>    try {</p><p>      f(i);</p><p>    } catch(Up) {</p><p>      cout &lt;&lt; "Up caught" &lt;&lt; endl;</p><p>    } catch(Fit) {</p><p>      cout &lt;&lt; "Fit caught" &lt;&lt; endl;</p><p>    }</p><p>} ///:~</p><empty-line/><p>The classes <strong>Up</strong> and <strong>Fit</strong> are created solely to throw as exceptions. Often exception classes will be small, but they can certainly hold additional information so that the handlers can query for it<sup>.</sup></p><p>The <strong>f( )</strong> function promises in its exception specification to throw only exceptions of type <strong>Up</strong> and <strong>Fit</strong>, and from looking at the function definition, this seems plausible. Version one of <strong>g( )</strong>, called by <strong>f( )</strong>, doesn’t throw any exceptions, so this is true. But if someone changes <strong>g( )</strong> so that it throws a different type of exception (like the second version in this example, which throws an <strong>int</strong>), the exception specification for <strong>f( )</strong> is violated<sup>.</sup></p><p>The <strong>my_unexpected( )</strong> function has no arguments or return value, following the proper form for a custom <strong>unexpected( )</strong> function. It simply displays a message so that you can see that it was called, and then exits the program (<strong>exit(0)</strong> is used here so that the book’s <strong>make</strong> process is not aborted). Your new <strong>unexpected( )</strong> function should not have a <strong>return</strong> statement<sup>.</sup></p><p>In <strong>main( )</strong>, the <strong>try</strong> block is within a <strong>for</strong> loop, so all the possibilities are exercised. In this way, you can achieve something like resumption. Nest the <strong>try</strong> block inside a <strong>for</strong>, <strong>while</strong>, <strong>do</strong>, or <strong>if</strong> and cause any exceptions to attempt to repair the problem; then attempt the <strong>try</strong> block again<sup>.</sup></p><p>Only the <strong>Up</strong> and <strong>Fit</strong> exceptions are caught because those are the only exceptions that the programmer of <strong>f( )</strong> said would be thrown. Version two of <strong>g( )</strong> causes <strong>my_unexpected( )</strong> to be called because <strong>f( )</strong> then throws an <strong>int</strong><sup><strong>.</strong></sup></p><p>In the call to <strong>set_unexpected( )</strong>, the return value is ignored, but it can also be saved in a pointer to function and be restored later, as we did in the <strong>set_terminate( )</strong> example earlier in this chapter<sup>.</sup></p><p>A typical <strong>unexpected</strong> handler logs the error and terminates the program by calling <strong>exit( )</strong>. It can, however, throw another exception (or re-throw the same exception) or call <strong>abort( )</strong>. If it throws an exception of a type allowed by the function whose specification was originally violated, the search resumes at the <emphasis>call</emphasis> of the function with this exception specification. (This behavior is unique to <strong>unexpected( )</strong>.)</p><p>If the exception thrown from your <strong>unexpected</strong> handler is not allowed by the original function’s specification, one of the following occurs:</p><p>1.       If <strong>std::bad_exception</strong> (defined in <strong>&lt;exception&gt;</strong>) was in the function’s exception specification, the exception thrown from the unexpected handler is replaced with a <strong>std::bad_exception</strong> object, and the search resumes from the function as before.</p><p>2.      If the original function’s specification did not include <strong>std::bad_exception</strong>, <strong>terminate( )</strong> is called.</p><p>The following program illustrates this behavior<sup>.</sup></p><p>//: C01:BadException.cpp</p><p>//{-bor}</p><p>#include &lt;exception&gt;    // for std::bad_exception</p><p>#include &lt;iostream&gt;</p><p>#include &lt;cstdio&gt;</p><p>using namespace std;</p><empty-line/><p>// Exception classes:</p><p>class A {};</p><p>class B {};</p><empty-line/><p>// terminate() handler</p><p>void my_thandler() {</p><p>  cout &lt;&lt; "terminate called\n";</p><p>  exit(0);</p><p>}</p><empty-line/><p>// unexpected() handlers</p><p>void my_uhandler1() {</p><p>  throw A();</p><p>}</p><p>void my_uhandler2() {</p><p>  throw;</p><p>}</p><empty-line/><p>// If we embed this throw statement in f or g,</p><p>// the compiler detects the violation and reports</p><p>// an error, so we put it in its own function.</p><p>void t() {</p><p>  throw B();</p><p>}</p><empty-line/><p>void f() throw(A) {</p><p>  t();</p><p>}</p><p>void g() throw(A, bad_exception) {</p><p>  t();</p><p>}</p><empty-line/><p>int main() {</p><p>  set_terminate(my_thandler);</p><p>  set_unexpected(my_uhandler1);</p><p>  try {</p><p>    f();</p><p>  }</p><p>  catch (A&amp;) {</p><p>    cout &lt;&lt; "caught an A from f\n";</p><p>  }</p><p>  set_unexpected(my_uhandler2);</p><p>  try {</p><p>    g();</p><p>  }</p><p>  catch (bad_exception&amp;) {</p><p>    cout &lt;&lt; "caught a bad_exception from g\n";</p><p>  }</p><p>  try {</p><p>    f();</p><p>  }</p><p>  catch (...) {</p><p>    cout &lt;&lt; "This will never print\n";</p><p>  }</p><p>} ///:~</p><empty-line/><p>The <strong>my_uhandler1( )</strong> handler throws an acceptable exception (<strong>A</strong>), so execution resumes at the first catch, which succeeds. The <strong>my_uhandler2( )</strong> handler does not throw a valid exception (<strong>B</strong>), but since <strong>g</strong> specifies <strong>bad_exception</strong>, the <strong>B</strong> exception is replaced by a <strong>bad_exception</strong> object, and the second catch also succeeds. Since <strong>f</strong> does not include <strong>bad_exception</strong> in its specification, <strong>my_thandler( )</strong> is called as a terminate handler. Thus, the output from this program is as follows:<sup>.</sup></p><p>caught an A from f</p><p>caught a bad_exception from g</p><p>terminate called</p><empty-line/></section></section></section><section><title><p>Better exception specifications?</p></title><p>You may feel that the existing exception specification rules aren’t very safe, and that</p><p>void f();</p><empty-line/><p><emphasis>should</emphasis> mean that no exceptions are thrown from this function. If the programmer wants to throw any type of exception, you might think he or she <emphasis>should </emphasis>have to say<sup>.</sup></p><p>void f() throw(...); // Not in C++</p><empty-line/><p>This would surely be an improvement because function declarations would be more explicit. Unfortunately, you can’t always know by looking at the code in a function whether an exception will be thrown—it could happen because of a memory allocation, for example. Worse, existing functions written before exception handling was introduced may find themselves inadvertently throwing exceptions because of the functions they call (which might be linked into new, exception-throwing versions). Hence, the uninformative situation whereby<sup>.</sup></p><p>void f();</p><empty-line/><p>means, "Maybe I’ll throw an exception, maybe I won’t." This ambiguity is necessary to avoid hindering code evolution. If you want to specify that <strong>f</strong> throws no exceptions, use the empty list, as in:<sup>.</sup></p><p>void f() throw();</p><empty-line/></section><section><title><p>Exception specifications and inheritance</p></title><p>Each public function in a class essentially forms a contract with the user; if you pass it certain arguments, it will perform certain operations and/or return a result. The same contract must hold true in derived classes; otherwise the expected "is-a" relationship between derived and base classes is violated. Since exception specifications are logically part of a function’s declaration, they too must remain consistent across an inheritance hierarchy. For example, if a member function in a base class says it will only throw an exception of type <strong>A</strong>, an override of that function in a derived class must not add any other exception types to the specification list, because that would result in unexpected exceptions for the user, breaking any programs that adhere to the base class interface. You can, however, specify <emphasis>fewer</emphasis> exceptions or <emphasis>none at all</emphasis>, since that doesn’t require the user to do anything differently. You can also specify anything that "is-a" <strong>A</strong> in place of <strong>A</strong> in the derived function’s specification. Here’s an example<sup>.</sup></p><p>// C01:Covariance.cpp</p><p>// Compile Only!</p><p>//{-msc}</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Base {</p><p>public:</p><p>  class BaseException {};</p><p>  class DerivedException : public BaseException {};</p><p>  virtual void f() throw (DerivedException) {</p><p>    throw DerivedException();</p><p>  }</p><p>  virtual void g() throw (BaseException) {</p><p>    throw BaseException();</p><p>  }</p><p>};</p><empty-line/><p>class Derived : public Base {</p><p>public:</p><p>  void f() throw (BaseException) {</p><p>    throw BaseException();</p><p>  }</p><p>  virtual void g() throw (DerivedException) {</p><p>    throw DerivedException();</p><p>  }</p><p>};</p><empty-line/><p>A compiler should flag the override of <strong>Derived::f( )</strong> with an error (or at least a warning) since it changes its exception specification in a way that violates the specification of <strong>Base::f( )</strong>. The specification for <strong>Derived::g( )</strong> is acceptable because <strong>DerivedException</strong> "is-a" <strong>BaseException</strong> (not the other way around). You can think of <strong>Base/Derived</strong> and <strong>BaseException/DerivedException</strong> as parallel class hierarchies; when you are in <strong>Derived</strong>, you can replace references to <strong>BaseException</strong> in exception specifications and return values with <strong>DerivedException</strong>. This behavior is called <emphasis>covariance</emphasis>  (since both sets of classes vary down their respective hierarchies together). (Reminder from Volume 1: parameter types are <emphasis>not</emphasis> covariant—you are not allowed to change the signature of an overridden virtual function.)<sup>.</sup></p></section><section><title><p>When <emphasis>not</emphasis> to use exception specifications</p></title><p>If you peruse the function declarations throughout the Standard C++ library, you’ll find that not a single exception specification occurs anywhere! Although this might seem strange, there is a good reason for this seeming incongruity: the library consists mainly of templates, and you never know what a generic might do. For example, suppose you are developing a generic stack template and attempt to affix an exception specification to your pop function, like this:</p><p>T pop() throw(logic_error);</p><empty-line/><p>Since the only error you anticipate is a stack underflow, you might think it’s safe to specify a <strong>logic_error</strong> or some other appropriate exception type. But since you don’t know much about the type <strong>T</strong>, what if its copy constructor could possibly throw an exception (it’s not unreasonable, after all)? Then <strong>unexpected( )</strong> would be called, and your program would terminate. The point is that you shouldn’t make guarantees that you can’t stand behind. If you don’t know what exceptions might occur, don’t use exception specifications. That’s why template classes, which constitute 90 percent of the Standard C++ library, do not use exception specifications—they specify the exceptions they know about in <emphasis>documentation</emphasis> and leave the rest to you. Exception specifications are mainly for non-template classes<sup>.</sup></p></section></section><section><title><p>Exception safety</p></title><p>In Chapter 7 we’ll take an in-depth look at the containers in the Standard C++ library, including the stack container. One thing you’ll notice is that the declaration of the <strong>pop( )</strong> member function looks like this:</p><p>void pop();</p><empty-line/><p>You might think it strange that <strong>pop( )</strong> doesn’t return a value. Instead, it just removes the element at the top of the stack. To retrieve the top value, call <strong>top( )</strong> before you call <strong>pop( )</strong>. There is an important reason for this behavior, and it has to do with <emphasis>exception safety</emphasis>, a crucial consideration in library design<sup>.</sup></p><p>Suppose you are implementing a stack with a dynamic array (we’ll call it <strong>data</strong> and the counter integer <strong>count</strong>), and you try to write <strong>pop( )</strong> so that it returns a value. The code for such a <strong>pop( )</strong> might look something like this:</p><p>template&lt;class T&gt;</p><p>T stack&lt;T&gt;::pop() {</p><p>  if (count == 0)</p><p>    throw logic_error("stack underflow");</p><p>  else</p><p>    return data[--count];</p><p>}</p><empty-line/><p>What happens if the copy constructor that is called for the return value in the last line throws an exception when the value is returned? The popped element is not returned because of the exception, and yet <strong>count</strong> has already been decremented, so the top element you wanted is lost forever! The problem is that this function attempts to do two things at once: (1) return a value, and (2) change the state of the stack. It is better to separate these two actions into two separate member functions, which is exactly what the standard <strong>stack</strong> class does. (In other words, follow the time-worn design practice of <emphasis>cohesion</emphasis>—every function should do <emphasis>one thing well</emphasis>.) Exception-safe code leaves objects in a consistent state and does not leak resources<sup>.</sup></p><p>You also need to be careful writing custom assignment operators. In Chapter 12 of Volume 1, you saw that <strong>operator=</strong> should adhere to the following pattern:</p><p>1.       Make sure you’re not assigning to self. If you are, go to step 6. (This is strictly an optimization.)</p><p>2.      Allocate new memory required by pointer data members.</p><p>3.      Copy data from the old memory to the new.</p><p>4.      Delete the old memory.</p><p>5.      Update the object’s state by assigning the new heap pointers to the pointer data members.</p><p>6.      Return <strong>*this</strong>.</p><p>It’s important to not change the state of your object until all the new pieces have been safely allocated and initialized. A good technique is to move all of steps 2 and 3 into a separate function, often called <strong>clone( )</strong>. The following example does this for a class that has two pointer members, <strong>theString</strong> and <strong>theInts</strong><sup><strong>.</strong></sup></p><p>//: C01:SafeAssign.cpp</p><p>// Shows an Exception-safe operator=</p><p>#include &lt;iostream&gt;</p><p>#include &lt;new&gt;       // For std::bad_alloc</p><p>#include &lt;cstring&gt;</p><p>using namespace std;</p><empty-line/><p>// A class that has two pointer members using the heap</p><p>class HasPointers {</p><p>  // A Handle class to hold the data</p><p>  struct MyData {</p><p>    const char* theString;</p><p>    const int* theInts;</p><p>    size_t numInts;</p><p>    MyData(const char* pString, const int* pInts,</p><p>           size_t nInts)</p><p>    : theString(pString), theInts(pInts),</p><p>    numInts(nInts) {}</p><p>  } *theData;  // The handle</p><empty-line/><p>  // clone and cleanup functions</p><p>  static MyData* clone(const char* otherString,</p><p>        const int* otherInts, size_t nInts){</p><p>    char* newChars = new char[strlen(otherString)+1];</p><p>    int* newInts;</p><p>    try {</p><p>      newInts = new int[nInts];</p><p>    } catch (bad_alloc&amp;) {</p><p>      delete [] newChars;</p><p>      throw;</p><p>    }</p><p>    try {</p><p>      // This example uses built-in types, so it won't</p><p>      // throw, but for class types it could throw, so we</p><p>      // use a try block for illustration. (This is the</p><p>      // point of the example!)</p><p>      strcpy(newChars, otherString);</p><p>      for (size_t i = 0; i &lt; nInts; ++i)</p><p>        newInts[i] = otherInts[i];</p><p>    } catch (...) {</p><p>      delete [] newInts;</p><p>      delete [] newChars;</p><p>      throw;</p><p>    }</p><p>    return new MyData(newChars, newInts, nInts);</p><p>  }</p><p>  static MyData* clone(const MyData* otherData) {</p><p>    return clone(otherData-&gt;theString,</p><p>  otherData-&gt;theInts,</p><p>  otherData-&gt;numInts);</p><p>  }</p><p>  static void cleanup(const MyData* theData) {</p><p>    delete [] theData-&gt;theString;</p><p>    delete [] theData-&gt;theInts;</p><p>    delete theData;</p><p>  }</p><p>public:</p><p>  HasPointers(const char* someString, const int* someInts,</p><p>              size_t numInts) {</p><p>    theData = clone(someString, someInts, numInts);</p><p>  }</p><p>  HasPointers(const HasPointers&amp; source) {</p><p>    theData = clone(source.theData);</p><p>  }</p><p>  HasPointers&amp; operator=(const HasPointers&amp; rhs) {</p><p>    if (this != &amp;rhs) {</p><p>      MyData* newData =</p><p>      clone(rhs.theData-&gt;theString,</p><p>            rhs.theData-&gt;theInts,</p><p>            rhs.theData-&gt;numInts);</p><p>      cleanup(theData);</p><p>      theData = newData;</p><p>    }</p><p>    return *this;</p><p>  }</p><p>  ~HasPointers() {</p><p>    cleanup(theData);</p><p>  }</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os,</p><p>              const HasPointers&amp; obj) {</p><p>    os &lt;&lt; obj.theData-&gt;theString &lt;&lt; ": ";</p><p>    for (size_t i = 0; i &lt; obj.theData-&gt;numInts; ++i)</p><p>      os &lt;&lt; obj.theData-&gt;theInts[i] &lt;&lt; ' ';</p><p>    return os;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  int someNums[] = {1, 2, 3, 4};</p><p>  size_t someCount = sizeof someNums / sizeof someNums[0];</p><p>  int someMoreNums[] = {5, 6, 7};</p><p>  size_t someMoreCount =</p><p>  sizeof someMoreNums / sizeof someMoreNums[0];</p><p>  HasPointers h1("Hello", someNums, someCount);</p><p>  HasPointers h2("Goodbye", someMoreNums, someMoreCount);</p><p>  cout &lt;&lt; h1 &lt;&lt; endl;  // Hello: 1 2 3 4</p><p>  h1 = h2;</p><p>  cout &lt;&lt; h1 &lt;&lt; endl;  // Goodbye: 5 6 7</p><p>} ///:~</p><empty-line/><p>For convenience, <strong>HasPointers</strong> uses the <strong>MyData</strong> class as a handle to the two pointers. Whenever it’s time to allocate more memory, whether during construction or assignment, the first <strong>clone</strong> function is ultimately called to do the job. If memory fails for the first call to the <strong>new</strong> operator, a <strong>bad_alloc</strong> exception is thrown automatically. If it happens on the second allocation (for <strong>theInts</strong>), we have to clean up the memory for <strong>theString</strong>—hence the first <strong>try</strong> block that catches a <strong>bad_alloc</strong> exception. The second <strong>try</strong> block isn’t crucial here because we’re just copying <strong>int</strong>s and pointers (so no exceptions will occur), but whenever you copy objects, their assignment operators can possibly cause an exception, in which case everything needs to be cleaned up. In both exception handlers, notice that we <emphasis>rethrow</emphasis> the exception. That’s because we’re just managing resources here; the user still needs to know that something went wrong, so we let the exception propagate up the dynamic chain. Software libraries that don’t silently swallow exceptions are called <emphasis>exception neutral</emphasis>. Always strive to write libraries that are both exception safe and exception neutral.<a l:href="#n6" type="note">[6]</a></p><p>If you inspect the previous code closely, you’ll notice that none of the <strong>delete</strong> operations will throw an exception. This code actually depends on that fact. Recall that when you call <strong>delete</strong> on an object, the object’s destructor is called. It turns out to be practically impossible, therefore, to design exception-safe code without assuming that destructors don’t throw exceptions. Don’t let destructors throw exceptions! (We’re going to remind you about this once more before this chapter is done)<a l:href="#n7" type="note">[7]</a> .</p></section><section><title><p>Programming with exceptions</p></title><section><p>For most programmers, especially C programmers, exceptions are not available in their existing language and take a bit of adjustment. Here are some guidelines for programming with exceptions<sup>.</sup></p></section><section><title><p>When to avoid exceptions</p></title><section><p>Exceptions aren’t the answer to all problems. In fact, if you simply go looking for something to pound with your new hammer, you’ll cause trouble. The following sections point out situations in which exceptions are <emphasis>not</emphasis> warranted. Probably the best advice for deciding when to use exceptions is to throw exceptions only when a function fails to meet its specification<sup>.</sup></p></section><section><section><title><p>Not for asynchronous events</p></title><p>The Standard C <strong>signal( )</strong> system and any similar system handle asynchronous events: events that happen outside the flow of a program, and thus events the program cannot anticipate. You cannot use C++ exceptions to handle asynchronous events because the exception and its handler are on the same call stack. That is, exceptions rely on the dynamic chain of function calls on the program’s runtime stack (dynamic scope, if you will), whereas asynchronous events must be handled by completely separate code that is not part of the normal program flow (typically, interrupt service routines or event loops). Don’t throw exceptions from interrupt handlers<sup>.</sup></p><p>This is not to say that asynchronous events cannot be <emphasis>associated</emphasis> with exceptions. But the interrupt handler should do its job as quickly as possible and then return. The typical way to handle this situation is to set a flag in the interrupt handler, and check it synchronously in the mainline code<sup>.</sup></p></section><section><title><p>Not for benign error conditions</p></title><p>If you have enough information to handle an error, it’s not an exception. Take care of it in the current context rather than throwing an exception to a larger context<sup>.</sup></p><p>Also, C++ exceptions are not thrown for machine-level events such as divide-by-zero.<a l:href="#n8" type="note">[8]</a> It’s assumed that some other mechanism, such as the operating system or hardware, deals with these events. In this way, C++ exceptions can be reasonably efficient, and their use is isolated to program-level exceptional conditions<sup>.</sup></p></section><section><title><p>Not for flow-of-control</p></title><p>An exception looks somewhat like an alternate return mechanism and somewhat like a <strong>switch</strong> statement, so you might be tempted to use an exception instead of these ordinary language mechanisms. This is a bad idea, partly because the exception-handling system is significantly less efficient than normal program execution; exceptions are a rare event, so the normal program shouldn’t pay for them. Also, exceptions from anything other than error conditions are quite confusing to the user of your class or function<sup>.</sup></p></section><section><title><p>You’re not forced to use exceptions</p></title><p>Some programs are quite simple (small utilities, for example). You might only need to take input and perform some processing. In these programs, you might attempt to allocate memory and fail, try to open a file and fail, and so on. It is acceptable in these programs to display a message and exit the program, allowing the system to clean up the mess, rather than to work hard to catch all exceptions and recover all the resources yourself. Basically, if you don’t need to use exceptions, you don’t have to use them<sup>.</sup></p></section><section><title><p>New exceptions, old code</p></title><p>Another situation that arises is the modification of an existing program that doesn’t use exceptions. You might introduce a library that <emphasis>does</emphasis> use exceptions and wonder if you need to modify all your code throughout the program. Assuming you have an acceptable error-handling scheme already in place, the most straightforward thing to do is surround the largest block that uses the new library (this might be all the code in <strong>main( )</strong>) with a <strong>try</strong> block, followed by a <strong>catch(...)</strong> and basic error message). You can refine this to whatever degree necessary by adding more specific handlers, but, in any case, the code you’re forced to add can be minimal. It’s even better, of course, to isolate your exception-generating code in a <strong>try</strong> block and write handlers to convert the exceptions into your existing error-handling scheme<sup>.</sup></p><p>It’s truly important to think about exceptions when you’re creating a library for someone else to use, especially in situations in which you can’t know how they need to respond to critical error conditions (recall the earlier discussions on exception safety and why there are no exception specifications in the Standard C++ Library)<sup>.</sup></p></section></section></section><section><title><p>Typical uses of exceptions</p></title><section><p>Do use exceptions to do the following:</p><p>·         Fix the problem and call the function which caused the exception again.</p><p>·         Patch things up and continue without retrying the function.</p><p>·         Do whatever you can in the current context and rethrow the <emphasis>same</emphasis> exception to a higher context.</p><p>·         Do whatever you can in the current context and throw a <emphasis>different</emphasis> exception to a higher context.</p><p>·         Terminate the program.</p><p>·         Wrap functions (especially C library functions) that use ordinary error schemes so they produce exceptions instead.</p><p>·         Simplify. If your exception scheme makes things more complicated, it is painful and annoying to use.</p><p>·         Make your library and program safer. This is a short-term investment (for debugging) and a long-term investment (for application robustness)<sup>.</sup></p></section><section><section><title><p>When to use exception specifications</p></title><p>The exception specification is like a function prototype: it tells the user to write exception-handling code and what exceptions to handle. It tells the compiler the exceptions that might come out of this function so that it can detect violations at runtime<sup>.</sup></p><p>Of course, you can’t always look at the code and anticipate which exceptions will arise from a particular function. Sometimes, the functions it calls produce an unexpected exception, and sometimes an old function that didn’t throw an exception is replaced with a new one that does, and you get a call to <strong>unexpected( )</strong>. Any time you use exception specifications or call functions that do, consider creating your own <strong>unexpected( )</strong> function that logs a message and then either throws an exception or aborts the program<sup>.</sup></p><p>As we explained earlier, you should avoid using exception specifications in template classes, since you can’t anticipate what types of exceptions the template parameter classes might throw<sup>.</sup></p></section><section><title><p>Start with standard exceptions</p></title><p>Check out the Standard C++ library exceptions before creating your own. If a standard exception does what you need, chances are it’s a lot easier for your user to understand and handle<sup>.</sup></p><p>If the exception type you want isn’t part of the standard library, try to derive one from an existing standard exception. It’s nice if your users can always write their code to expect the <strong>what( ) </strong>function defined in the <strong>exception( )</strong> class interface<sup>.</sup></p></section><section><title><p>Nest your own exceptions</p></title><p>If you create exceptions for your particular class, it’s a good idea to nest the exception classes either inside your class or inside a namespace containing your class, to provide a clear message to the reader that this exception is used only for your class. In addition, it prevents the pollution of the global namespace<sup>.</sup></p><p>You can nest your exceptions even if you’re deriving them from C++ standard exceptions<sup>.</sup></p></section><section><title><p>Use exception hierarchies</p></title><p>Using exception hierarchies is a valuable way to classify the types of critical errors that might be encountered with your class or library. This gives helpful information to users, assists them in organizing their code, and gives them the option of ignoring all the specific types of exceptions and just catching the base-class type. Also, any exceptions added later by inheriting from the same base class will not force all existing code to be rewritten—the base-class handler will catch the new exception<sup>.</sup></p><p>Of course, the Standard C++ exceptions are a good example of an exception hierarchy and one on which you can build<sup>.</sup></p></section><section><title><p>Multiple inheritance (MI)</p></title><p>As you’ll read in Chapter 9, the only <emphasis>essential </emphasis>place for MI is if you need to upcast an object pointer to two different base classes—that is, if you need polymorphic behavior with both of those base classes. It turns out that exception hierarchies are useful places for multiple inheritance because a base-class handler from any of the roots of the multiply inherited exception class can handle the exception<sup>.</sup></p></section><section><title><p>Catch by reference, not by value</p></title><p>We explained in the section "Exception matching" earlier that you should catch exceptions by reference for two reasons:</p><p>·         To avoid making a needless copy of the exception object when it is passed to the handler,</p><p>·         To avoid object slicing when catching a derived exception as a base class object</p><p>Although you can also throw and catch pointers, by doing so you introduce more coupling—the thrower and the catcher must agree on how the exception object is allocated and cleaned up. This is a problem because the exception itself might have occurred from heap exhaustion. If you throw exception objects, the exception-handling system takes care of all storage<sup>.</sup></p></section><section><title><p>Throw exceptions in constructors</p></title><p>Because a constructor has no return value, you’ve previously had two ways to report an error during construction:<sup>.</sup></p><p>·         Set a nonlocal flag and hope the user checks it.</p><p>·         Return an incompletely created object and hope the user checks it.</p><p>This problem is serious because C programmers have come to rely on an implied guarantee that object creation is always successful, which is not unreasonable in C in which types are so primitive. But continuing execution after construction fails in a C++ program is a guaranteed disaster, so constructors are one of the most important places to throw exceptions—now you have a safe, effective way to handle constructor errors. However, you must also pay attention to pointers inside objects and the way cleanup occurs when an exception is thrown inside a constructor<sup>.</sup></p></section><section><title><p>Don’t cause exceptions in destructors</p></title><p>Because destructors are called in the process of throwing other exceptions, you’ll never want to throw an exception in a destructor or cause another exception to be thrown by some action you perform in the destructor. If this happens, a new exception can be thrown <emphasis>before</emphasis> the catch-clause for an existing exception is reached, which will cause a call to <strong>terminate( )</strong><sup><strong>.</strong></sup></p><p>If you call any functions inside a destructor that can throw exceptions, those calls should be within a <strong>try</strong> block in the destructor, and the destructor must handle all exceptions itself. None must escape from the destructor<sup>.</sup></p></section><section><title><p>Avoid naked pointers</p></title><p>See <strong>Wrapped.cpp</strong> earlier in this chapter. A naked pointer usually means vulnerability in the constructor if resources are allocated for that pointer. A pointer doesn’t have a destructor, so those resources aren’t released if an exception is thrown in the constructor. Use <strong>auto_ptr</strong> for pointers that reference heap memory<sup>.</sup></p></section></section></section></section><section><title><p>Overhead</p></title><p>When an exception is thrown, there’s considerable runtime overhead (but it’s <emphasis>good overhead</emphasis>, since objects are cleaned up automatically!). For this reason, you never want to use exceptions as part of your normal flow-of-control, no matter how tempting and clever it may seem. Exceptions should occur only rarely, so the overhead is piled on the exception and not on the normally executing code. One of the important design goals for exception handling was that it could be implemented with no impact on execution speed when it <emphasis>wasn’t</emphasis> used; that is, as long as you don’t throw an exception, your code runs as fast as it would without exception handling. Whether this is actually true depends on the particular compiler implementation you’re using. (See the description of the "zero-cost model" later in this section.)<sup>.</sup></p><p>You can think of a <strong>throw</strong> expression as a call to a special system function that takes the exception object as an argument and backtracks up the chain of execution. For this to work, extra information needs to be put on the stack by the compiler, to aid in stack unwinding. To understand this, you need to know about the runtime stack. Whenever a function is called, information about that function is pushed onto the runtime stack in an <emphasis>activation record instance</emphasis> (ARI), also called a <emphasis>stack frame</emphasis>. A typical stack frame contains the address of the calling function (so execution can return to it), a pointer to the ARI of the function’s static parent (the scope that lexically contains the called function, so variables global to the function can be accessed), and a pointer to the function that called it (its <emphasis>dynamic parent</emphasis>). The path that logically results from repetitively following the dynamic parent links is the <emphasis>dynamic chain</emphasis>, or <emphasis>call chain</emphasis>, that we’ve mentioned previously in this chapter. This is how execution can backtrack when an exception is thrown, and it is the mechanism that makes it possible for components developed without knowledge of one another to communicate errors at runtime<sup>.</sup></p><p>To enable stack unwinding for exception handling, extra exception-related information about each function needs to be available for each stack frame. This information describes which destructors need to be called (so that local objects can be cleaned up), indicates whether the current function has a <strong>try</strong> block, and lists which exceptions the associated catch clauses can handle. Naturally there is space penalty for this extra information, so programs that support exception handling can be somewhat larger than those that don’t.<a l:href="#n9" type="note">[9]</a>Even the compile-time size of programs using exception handling is greater, since the logic of how to generate the expanded stack frames during runtime must be generated by the compiler<sup>.</sup></p><p>To illustrate this, we compiled the following program both with and without exception-handling support in Borland C++ Builder and Microsoft Visual C++<a l:href="#n10" type="note">[10]</a>.</p><p>struct HasDestructor {</p><p>  ~HasDestructor(){}</p><p>};</p><empty-line/><p>void g();      // for all we know, g may throw</p><empty-line/><p>void f() {</p><p>   HasDestructor h;</p><p>   g();</p><p>}</p><empty-line/><p>If exception handling is enabled, the compiler must keep information about <strong>~HasDestructor( )</strong> available at runtime in the ARI for <strong>f( )</strong> (so it can destroy <strong>h</strong> properly should <strong>g( )</strong> throw an exception). The following table summarizes the result of the compilations in terms of the size of the compiled (.obj) files (in bytes)<sup>.</sup></p><table><tr align="left"><td align="left" valign="top">Compiler\Mode</td><td align="left" valign="top">With Exception Support</td><td align="left" valign="top">Without Exception Support</td></tr><tr align="left"><td align="left" valign="top">Borland</td><td align="left" valign="top">616</td><td align="left" valign="top">234</td></tr><tr align="left"><td align="left" valign="top">Microsoft</td><td align="left" valign="top">1162</td><td align="left" valign="top">680</td></tr></table><empty-line/><p>Don’t take the percentage differences between the two modes too seriously. Remember that exceptions (should) typically constitute a small part of a program, so the space overhead tends to be much smaller (usually between 5 and 15 percent).</p><p>You might think that this extra housekeeping would slow down execution, and you’d be correct. A clever compiler implementation can avoid that cost, however. Since information about exception-handling code and the offsets of local objects can be computed once at compile time, such information can be kept in a single place associated with each function, but not in each ARI. You essentially remove exception overhead from each ARI and, therefore, avoid the extra time to push them onto the stack. This approach is called the <emphasis>zero-cost</emphasis> model<a l:href="#n11" type="note">[11]</a> of exception handling, and the optimized storage mentioned earlier is known as the <emphasis>shadow stack</emphasis>.<a l:href="#n12" type="note">[12]</a></p></section><section><title><p>Summary</p></title><p>Error recovery is a fundamental concern for every program you write, and it’s especially important in C++, in which one of the goals is to create program components for others to use. To create a robust system, each component must be robust<sup>.</sup></p><p>The goals for exception handling in C++ are to simplify the creation of large, reliable programs using less code than currently possible, with more confidence that your application doesn’t have an unhandled error. This is accomplished with little or no performance penalty and with low impact on existing code<sup>.</sup></p><p>Basic exceptions are not terribly difficult to learn; begin using them in your programs as soon as you can. Exceptions are one of those features that provide immediate and significant benefits to your project<sup>.</sup></p></section><section><title><p>Exercises</p></title><p>             4.             Create a class with member functions that throw exceptions. Within this class, make a nested class to use as an exception object. It takes a single <strong>char*</strong> as its argument; this represents a description string. Create a member function that throws this exception. (State this in the function’s exception specification.) Write a <strong>try</strong> block that calls this function and a <strong>catch</strong> clause that handles the exception by displaying its description string.</p><p>             5.             Rewrite the Stash class from Chapter 13 of Volume 1 so that it throws <strong>out_of_range</strong> exceptions for <strong>operator[]</strong>.</p><p>             6.             Write a generic <strong>main( )</strong> that takes all exceptions and reports them as errors.</p><p>             7.             Create a class with its own <strong>operator new</strong>. This operator should allocate ten objects, and on the eleventh object "run out of memory" and throw an exception. Also add a <strong>static</strong> member function that reclaims this memory. Now create a <strong>main( )</strong> with a <strong>try</strong> block and a <strong>catch</strong> clause that calls the memory-restoration routine. Put these inside a <strong>while</strong> loop, to demonstrate recovering from an exception and continuing execution.</p><p>             8.             Create a destructor that throws an exception, and write code to prove to yourself that this is a bad idea by showing that if a new exception is thrown before the handler for the existing one is reached, <strong>terminate( )</strong> is called.</p><p>             9.             Prove to yourself that all exception objects (the ones that are thrown) are properly destroyed.</p><p>        10.             Prove to yourself that if you create an exception object on the heap and throw the pointer to that object, it will not be cleaned up.</p><p>         11.             Write a function with an exception specification that can throw four exception types: a <strong>char</strong>, an <strong>int</strong>, a <strong>bool</strong>, and your own exception class. Catch each in <strong>main( )</strong> and verify the catch. Derive your exception class from a standard exception. Write the function in such a way that the system recovers and tries to execute it again.</p><p>         12.             Modify your solution to the exercise 8 to throw a double from the function, violating the exception specification. Catch the violation with your own unexpected handler that displays a message and exits the program gracefully (meaning <strong>abort( )</strong> is not called).</p><p>         13.             Write a <strong>Garage</strong> class that has a <strong>Car</strong> that is having troubles with its <strong>Motor</strong>. Use a function-level <strong>try</strong> block in the <strong>Garage</strong> class constructor to catch an exception (thrown from the <strong>Motor</strong> class) when its <strong>Car</strong> object is initialized. Throw a different exception from the body of the <strong>Garage</strong> constructor’s handler and catch it in <strong>main( )</strong>.</p></section></section><section><title><p>2: Defensive programming</p></title><section><p>Writing "perfect software" may be an elusive Holy Grail for developers, but a few defensive techniques, routinely applied, can go a long way toward narrowing the gap between code and ideal.</p><p>Although the complexity of typical production software guarantees that testers will always have a job, chances are you still yearn to produce defect-free software. (At least we hope you do!) Object-oriented design techniques do much to corral the difficulty of large projects, to be sure. Eventually, however, you have to get down to writing loops and functions. These details of "programming in the small" become the building blocks of the implementation of larger components called for by your design efforts. If your loops are off by one or your functions calculate the correct values only "most" of the time, you’re in deep trouble no matter how fancy your overall methodology. In this chapter, we’re interested in coding practices that keep you on track toward a working solution regardless of the size of your project<sup>.</sup></p><p>Your code is, among other things, an expression of your attempt to solve a problem. It should be clear to the reader (including yourself) exactly what you were thinking when you designed that loop. At certain points in your program, you should be able to make bold statements that some condition or other holds. (If you can’t, you really haven’t yet solved the problem.) Such statements are called <emphasis>invariants</emphasis>, since they should invariably be true at the point where they appear in the code; if not, either your design is faulty, or your code does not accurately reflect your design. (In other words, you’ve got bugs!)<sup>.</sup></p><p>To illustrate, consider how to write a program that plays the guessing game of Hi-lo. You play this game by having one person think of a number between 1 and 100, and having the other person guess the number. (We’ll let the computer do the guessing.) The person who holds the number tells the guesser whether their guess is high, low or correct. The best strategy for the guesser is of course <emphasis>binary search</emphasis>, which chooses the midpoint of the range of numbers where the sought-after number resides. The high-low response tells the guesser which half of the list holds the number, and the process repeats, halving the size of the active search range on each iteration. So how do you write a loop to drive the repetition properly? It’s not sufficient to just say<sup>.</sup></p><p>bool guessed = false;</p><p>while (!guessed) {</p><p>  …</p><p>}</p><empty-line/><p>because a malicious user might respond deceitfully, and you could spend all day guessing. What assumption, however simple, are you making each time you guess? In other words, what condition should hold <emphasis>by design</emphasis> on each loop iteration?<sup>.</sup></p><p>The simple assumption we’re after is, of course, that the secret number is within the current active range of unguessed numbers, beginning with the range [1, 100]. Suppose we label the endpoints of the range with the variables <emphasis><strong>low</strong></emphasis> and <emphasis><strong>high</strong></emphasis>. Each time you pass through the loop you need to make sure that if the number was in the range [<strong>low</strong>, <strong>high</strong>] at the beginning of the loop, you calculate the new range so that it still contains the number at the end of the current loop iteration<sup>.</sup></p><p>The goal is to express the loop invariant in code so that a violation can be detected at runtime. Unfortunately, since the computer doesn’t know the secret number, you can’t express this condition directly in code, but you can at least make a comment to that effect:</p><p>while (!guessed) {</p><p>  // INVARIANT: the number is in the range [low, high]</p><p>  …</p><p>}</p><empty-line/><p>If we were to stop this thread of discussion right here, we would have accomplished a great deal if it helps clarify how you design loops. Fortunately, we can do better than that. What happens when the user says that a guess is too high when it isn’t or that it’s too low when it in fact is not? The deception will in effect exclude the secret number from the new subrange. Because one lie always leads to another, eventually your range will diminish to nothing (since you shrink it by half each time and the secret number isn’t in there). We can easily express this condition concretely, as the following program illustrates<sup>.</sup></p><p>//: C02:HiLo.cpp</p><p>// Plays the game of Hi-lo to illustrate a loop invariant</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  cout &lt;&lt; "Think of a number between 1 and 100\n";</p><p>cout &lt;&lt; "I will make a guess; ";</p><p>cout &lt;&lt; "tell me if I'm (H)igh or (L)ow\n";</p><p>  int low = 1, high = 100;</p><p>  bool guessed = false;</p><p>  while (!guessed) {</p><p>    // Invariant: the number is in the range [low, high]</p><p>    if (low &gt; high) {  // Invariant violation</p><p>      cout &lt;&lt; "You cheated! I quit\n";</p><p>      return EXIT_FAILURE;</p><p>    }</p><p>    int guess = (low + high) / 2;</p><p>    cout &lt;&lt; "My guess is " &lt;&lt; guess &lt;&lt; ". ";</p><p>    cout &lt;&lt; "(H)igh, (L)ow, or (E)qual? ";</p><p>    string response;</p><p>    cin &gt;&gt; response;</p><p>    switch(toupper(response[0])) {</p><p>      case 'H':</p><p>        high = guess - 1;</p><p>        break;</p><p>      case 'L':</p><p>        low = guess + 1;</p><p>        break;</p><p>      case 'E':</p><p>        guessed = true;</p><p>        break;</p><p>      default:</p><p>        cout &lt;&lt; "Invalid response\n";</p><p>        continue;</p><p>    }</p><p>  }</p><p>  cout &lt;&lt; "I got it!\n";</p><p>  return EXIT_SUCCESS;</p><p>} ///:~</p><empty-line/><p>The violation of the invariant is easily detected with the condition <strong>if (low &gt; high)</strong>, because if the user always tells the truth, we will always find the secret number before we run out of numbers to guess from. (See the last paragraph of the text that follows the program <strong>extractCode.cpp</strong> at the end of Chapter 3 for an explanation of the macros <strong>EXIT_FAILURE</strong> and <strong>EXIT_SUCCESS</strong>)<sup>.</sup></p></section><section><title><p>Assertions</p></title><p>The condition in the Hi-lo program depends on user input, so you’re powerless to always prevent a violation of the invariant. Most often, however, invariants depend only on the code you write, so they will always hold, if you’ve implemented your design correctly. In this case, it is clearer to make an <emphasis>assertion</emphasis>, which is a positive statement that reveals your design decisions<sup>.</sup></p><p>For example, suppose you are implementing a vector of integers, which, as you know, is an expandable array that grows on demand. The function that adds an element to the vector must first verify that there is an open slot in the underlying array that holds the elements; otherwise, it needs to request more heap space and copy the existing elements to the new space before adding the new element (and of course deleting the old array). Such a function might look like the following:<sup>.</sup></p><p>void MyVector::push_back(int x) {</p><p>   if (nextSlot == capacity)</p><p>      grow();</p><p>   assert(nextSlot &lt; capacity);</p><p>   data[nextSlot++] = x;</p><p>}</p><empty-line/><p>In this example, <strong>data</strong> is a dynamic array of <strong>int</strong>s with <strong>capacity</strong> slots and <strong>nextSlot</strong> slots in use. The purpose of <strong>grow( )</strong> is to expand the size of <strong>data</strong> so that the new value of <strong>capacity</strong> is strictly greater than <strong>nextSlot</strong>. Proper behavior of <strong>MyVector</strong> depends on this design decision, and it will never fail if the rest of the supporting code is correct, so we <emphasis>assert</emphasis> the condition with the <strong>assert( )</strong> macro (defined in the header <strong>&lt;cassert&gt;</strong>)<sup>.</sup></p><p>The Standard C library <strong>assert( )</strong> macro is brief, to the point, and portable. If the condition in its parameter evaluates to non-zero, execution continues uninterrupted; if it doesn’t, a message containing the text of the offending expression along with its source file name and line number is printed to the standard error channel and the program aborts. Is that too drastic? In practice, it is much more drastic to let execution continue when a basic design assumption has failed. Your program needs to be fixed<sup>.</sup></p><p>If all goes well, you will have thoroughly tested your code with all assertions intact by the time the final product is deployed. (We’ll say more about testing later.) Depending on the nature of your application, the machine cycles needed to test all assertions at runtime might be too much of a performance hit in the field. If that’s the case, you can remove all the assertion code automatically by defining the macro <strong>NDEBUG</strong> and rebuilding the application<sup>.</sup></p><p>To see how this works, note that a typical implementation of <strong>assert( )</strong> looks something like this:</p><p>#ifdef NDEBUG</p><p>  #define assert(cond) ((void)0)</p><p>#else</p><p>  void assertImpl(const char*, const char*, long);</p><p>#define assert(cond) \</p><p>  ((cond) ? (void)0 : assertImpl(???))</p><p>#endif</p><empty-line/><p>When the macro <strong>NDEBUG</strong> is defined, the code decays to the expression <strong>(void) 0</strong>, so all that’s left in the compilation stream is an essentially empty statement as a result of the semicolon you appended to each <strong>assert( )</strong> invocation. If <strong>NDEBUG</strong> is not defined, <strong>assert(cond)</strong> expands to a conditional statement that, when <strong>cond</strong> is zero, calls a compiler-dependent function (which we named <strong>assertImpl( )</strong>) with a string argument representing the text of <strong>cond</strong>, along with the file name and line number where the assertion appeared. (We used "???" as a place holder in the example, but the string mentioned is actually computed there, along with the file name and the line number where the macro occurs in that file. How these values are obtained is immaterial to our discussion.) If you want to turn assertions on and off at different points in your program, you not only have to <strong>#define</strong> or <strong>#undef NDEBUG</strong>, but you have to re-include <strong>&lt;cassert&gt;</strong>. Macros are evaluated as the preprocessor encounters them and therefore use whatever <strong>NDEBUG</strong> state applies at that point in time. The most common way to define <strong>NDEBUG</strong> once for an entire program is as a compiler option, whether through project settings in your visual environment or via the command line, as in</p><p>mycc –DNDEBUG myfile.cpp</p><empty-line/><p>Most compilers use the –<strong>D</strong> flag to define macro names. (Substitute the name of your compiler’s executable for <strong>mycc</strong> above.) The advantage of this approach is that you can leave your assertions in the source code as an invaluable bit of documentation, and yet there is no runtime penalty. Because the code in an assertion disappears when <strong>NDEBUG</strong> is defined, it is important that you <emphasis>never do work in an assertion</emphasis>. Only test conditions that do not change the state of your program<sup>.</sup></p><p>Whether using <strong>NDEBUG</strong> for released code is a good idea remains a subject of debate. Tony Hoare, one of the most influential computer scientists of all time,<a l:href="#n13" type="note">[13]</a> has suggested that turning off runtime checks such as assertions is similar to a sailing enthusiast who wears a life jacket while training on land and then discards it when he actually goes to sea.<a l:href="#n14" type="note">[14]</a> If an assertion fails in production, you have a problem much worse than degradation in performance, so choose wisely<sup>.</sup></p><p>Not all conditions should be enforced by assertions, of course. User errors and runtime resource failures should be signaled by throwing exceptions, as we explained in detail in Chapter 1. It is tempting to use assertions for most error conditions while roughing out code, with the intent to replace many of them later with robust exception handling. Like any other temptation, use caution, since you might forget to make all the necessary changes later. Remember: assertions are intended to verify design decisions that will only fail because of faulty programmer logic. The ideal is to solve all assertion violations during development. Don’t use assertions for conditions that aren’t totally in your control (for example, conditions that depend on user input). In particular, you wouldn’t want to use assertions to validate function arguments; throw a <strong>logic_error</strong> instead<sup>.</sup></p><p>The use of assertions as a tool to ensure program correctness was formalized by Bertrand Meyer in his <emphasis>Design by Contract</emphasis> methodology.<a l:href="#n15" type="note">[15]</a> Every function has an implicit contract with clients that, given certain <emphasis>pre-conditions</emphasis>, guarantees certain <emphasis>post-conditions</emphasis>. In other words, the pre-conditions are the requirements for using the function, such as supplying arguments within certain ranges, and the post-conditions are the results delivered by the function, either by return value or by side-effect<sup>.</sup></p><p>What should you do when clients fail to give you valid input? They have broken the contract, and you need to let them know. As we mentioned earlier, this is not the best time to abort the program (although you’re justified in doing so since the contract was violated), but an exception is certainly in order. This is why the Standard C++ library throws exceptions derived from <strong>logic_error</strong>, such as <strong>out_of_range</strong>.<a l:href="#n16" type="note">[16]</a> If there are functions that only you call, however, such as private functions in a class of your own design, the <strong>assert( )</strong> macro is appropriate, since you have total control over the situation and you certainly want to debug your code before shipping<sup>.</sup></p><p>Since post-conditions are totally your responsibility, you might think assertions also apply, and you would be partially right. It is appropriate to use an assertion for <emphasis>any invariant at any time</emphasis>, including when a function has finished its work. This especially applies to class member functions that maintain the state of an object. In the <strong>MyVector</strong> example earlier, for instance, a reasonable invariant for all public member functions would be</p><p>assert(0 &lt;= nextSlot &amp;&amp; nextSlot &lt;= capacity);</p><empty-line/><p>or, if <strong>nextSlot</strong> is an unsigned integer, simply</p><p>assert(nextSlot &lt;= capacity);</p><empty-line/><p>Such an invariant is called a <emphasis>class invariant</emphasis> and can reasonably be enforced by an assertion. Subclasses play the role of <emphasis>subcontractor</emphasis> to their base classes in that they must maintain the original contract the base class has with its clients. For this reason, the pre-conditions in derived classes must impose no extra requirements beyond those in the base contract, and the post-conditions must deliver at least as much.<a l:href="#n17" type="note">[17]</a></p><p>Validating results returned to the client, however, is nothing more or less than <emphasis>testing</emphasis>, so using post-condition assertions in this case would be duplicating work. There’s nothing wrong with it; it’s just an exercise in redundancy. Yes, it’s good documentation, but more than one developer has been fooled into using post-condition assertions as a <emphasis>substitute</emphasis> for unit testing. Bad idea!<sup>.</sup></p></section><section><title><p>A simple unit test framework</p></title><section><p>Writing software is all about meeting requirements.<a l:href="#n18" type="note">[18]</a> It doesn’t take much experience, however, to figure out that coming up with requirements in the first place is no easy task, and, more important, requirements are not static. It’s not unheard of to discover at a weekly project meeting that what you just spent the week doing is not exactly what the users really want<sup>.</sup></p><p>Frustrating? Yes. Reasonable? Also, yes! It is unreasonable to expect mere humans to be able to articulate software requirements in detail without sampling an evolving, working system. It's much better to specify a little, design a little, code a little, test a little. Then, after evaluating the outcome, do it all over again. The ability to develop from soup to nuts in such an iterative fashion is one of the great advances of this object-oriented era in software history. It requires nimble programmers who can craft resilient code. Change is hard<sup>.</sup></p><p>Ironically, another impetus for change comes from you, the programmer. The craftsperson in you likely has the habit of continually improving the physical design of working code. What maintenance programmer hasn’t had occasion to curse the aging, flagship company product as a convoluted patchwork of spaghetti, wholly resistant to modification? Management’s knee-jerk reluctance to let you tamper with a functioning system, while not totally unfounded, robs code of the resilience it needs to endure. "If it’s not broken, don’t fix it" eventually gives way to, "We can’t fix it—rewrite it." Change is necessary<sup>.</sup></p><p>Fortunately, our industry has finally gotten used to the discipline of <emphasis>refactoring</emphasis>, the art of internally restructuring code to improve its design, without changing the functionality visible to the user.<a l:href="#n19" type="note">[19]</a> Such tweaks include extracting a new function from another, or its inverse, combining member functions; replacing a member function with an object; parameterizing a member function or class; and replacing conditionals with polymorphism. Refactoring helps code embrace evolution<sup>.</sup></p><p>Whether the force for change comes from users or programmers, however, there is still the risk that changes today will break what worked yesterday. What is needed is a way to build code that withstands the winds of change and actually improves over time<sup>.</sup></p><p>Many practices purport to support such a quick-on-your-feet motif, of which Extreme Programming is only one.<a l:href="#n20" type="note">[20]</a> In this section we explore what we think is the key to making flexible, incremental development succeed: a ridiculously easy-to-use automated unit test framework. (Please note that we in no way mean to de-emphasize the role of <emphasis>testers</emphasis>, software professionals who test others’ code for a living. They are indispensable. We are merely describing a way to help developers write better code.)<sup>.</sup></p><p>Developers write <emphasis>unit tests</emphasis> to gain the confidence to say the two most important things that any developer can say:</p><p>1.I understand the requirements.</p><p>2.My code meets those requirements to the best of my knowledge.</p><p>There is no better way to ensure that you know what the code you're about to write should do than to write the unit tests first. This simple exercise helps focus the mind on the task ahead and will likely lead to working code faster than just jumping into coding. Or, to express it in XP terms: Testing + Programming is <emphasis>faster</emphasis> than just Programming. Writing tests first also puts you on guard up front against boundary conditions that might cause your code to break, so your code is more robust right out of the chute<sup>.</sup></p><p>Once your code passes all your tests, you have the peace of mind that if the system you contribute to isn't working, it's not your fault. The statement "All my tests pass" is a powerful trump card in the workplace that cuts through any amount of politics and hand waving<sup>.</sup></p></section><section><title><p>Automated testing</p></title><p>So what does a unit test look like? Too often developers just use some well-behaved input to produce some expected output, which they inspect visually. Two dangers exist in this approach. First, programs don't always receive only well-behaved input. We all know that we should test the boundaries of program input, but it's hard to think about this when you're trying to just get things working. If you write the test for a function first before you start coding, you can wear your "tester hat" and ask yourself, "What could possibly make this break?" Code a test that will prove the function you'll write isn't broken, and then put on your developer hat and make it happen. You'll write better code than if you hadn't written the test first<sup>.</sup></p><p>The second danger is that inspecting output visually is tedious and error prone. Most any such thing a human can do a computer can do, but without human error. It's better to formulate tests as collections of <emphasis>Boolean expressions</emphasis> and have a test program report any failures<sup>.</sup></p><p>For example, suppose you need to build a <strong>Date</strong> class that has the following properties:</p><p>·         A date can be initialized with a string (YYYYMMDD), three integers (Y, M, D), or nothing (giving today's date).</p><p>·         A date object can yield its year, month, and day or a string of the form "YYYYMMDD".</p><p>·         All relational comparisons are available, as well as computing the duration between two dates (in years, months, and days).</p><p>·         Dates to be compared need to be able to span an arbitrary number of centuries (for example, 1600–2200).</p><p>Your class can store three integers representing the year, month, and day. (Just be sure the year is at least 16 bits in size to satisfy the last bulleted item.) The interface for your <strong>Date</strong> class might look like this:<sup>.</sup></p><p>// A first pass at Date.h</p><p>#ifndef DATE_H</p><p>#define DATE_H</p><p>#include &lt;string&gt;</p><empty-line/><p>class Date {</p><p>public:</p><p>  // A struct to hold elapsed time:</p><p>  struct Duration {</p><p>    int years;</p><p>    int months;</p><p>    int days;</p><p>    Duration(int y, int m, int d)</p><p>      : years(y), months(m), days(d) {}</p><p>  };</p><p>  Date();</p><p>  Date(int year, int month, int day);</p><p>  Date(const std::string&amp;);</p><p>  int getYear() const;</p><p>  int getMonth() const;</p><p>  int getDay() const;</p><p>  std::string toString() const;</p><p>friend bool operator&lt;(const Date&amp;, const Date&amp;);</p><p>friend bool operator&gt;(const Date&amp;, const Date&amp;);</p><p>friend bool operator&lt;=(const Date&amp;, const Date&amp;);</p><p>friend bool operator&gt;=(const Date&amp;, const Date&amp;);</p><p>friend bool operator==(const Date&amp;, const Date&amp;);</p><p>friend bool operator!=(const Date&amp;, const Date&amp;);</p><p>  friend Duration duration(const Date&amp;, const Date&amp;);</p><p>};</p><p>#endif</p><empty-line/><p>Before you even think about implementation, you can solidify your grasp of the requirements for this class by writing the beginnings of a test program. You might come up with something like the following:</p><p>//: C02:SimpleDateTest.cpp</p><p>//{L} Date</p><p>// You’ll need the full Date.h from the Appendix:</p><p>#include "Date.h"</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>// Test machinery</p><p>int nPass = 0, nFail = 0;</p><p>void test(bool t) {</p><p>  if(t) nPass++; else nFail++;</p><p>}</p><empty-line/><p>int main() {</p><p>  Date mybday(1951, 10, 1);</p><p>  test(mybday.getYear() == 1951);</p><p>  test(mybday.getMonth() == 10);</p><p>  test(mybday.getDay() == 1);</p><p>  cout &lt;&lt; "Passed: " &lt;&lt; nPass &lt;&lt; ", Failed: "</p><p>       &lt;&lt; nFail &lt;&lt; endl;</p><p>}</p><p>/* Expected output:</p><p>Passed: 3, Failed: 0</p><p>*/ ///:~</p><empty-line/><p>In this trivial case, the function <strong>test( )</strong> maintains the global variables <strong>nPass</strong> and <strong>nFail</strong>. The only visual inspection you do is to read the final score. If a test failed, a more sophisticated <strong>test( )</strong> displays an appropriate message. The framework described later in this chapter has such a test function, among other things<sup>.</sup></p><p>You can now implement enough of the <strong>Date</strong> class to get these tests to pass, and then you can proceed iteratively in like fashion until all the requirements are met. By writing tests first, you are more likely to think of corner cases that might break your upcoming implementation, and you’re more likely to write the code correctly the first time. Such an exercise might produce the following "final" version of a test for the <strong>Date</strong> class:<sup>.</sup></p><p>//: C02:SimpleDateTest2.cpp</p><p>//{L} Date</p><p>#include &lt;iostream&gt;</p><p>#include "Date.h"</p><p>using namespace std;</p><empty-line/><p>// Test machinery</p><p>int nPass = 0, nFail = 0;</p><p>void test(bool t) {</p><p>  if(t) nPass++; else nFail++;</p><p>}</p><empty-line/><p>int main() {</p><p>  Date mybday(1951, 10, 1);</p><p>  Date today;</p><p>Date myevebday("19510930");</p><empty-line/><p>  // Test the operators</p><p>  test(mybday &lt; today);</p><p>  test(mybday &lt;= today);</p><p>  test(mybday != today);</p><p>  test(mybday == mybday);</p><p>  test(mybday &gt;= mybday);</p><p>  test(mybday &lt;= mybday);</p><p>  test(myevebday &lt; mybday);</p><p>  test(mybday &gt; myevebday);</p><p>  test(mybday &gt;= myevebday);</p><p>  test(mybday != myevebday);</p><empty-line/><p>  // Test the functions</p><p>  test(mybday.getYear() == 1951);</p><p>  test(mybday.getMonth() == 10);</p><p>  test(mybday.getDay() == 1);</p><p>  test(myevebday.getYear() == 1951);</p><p>  test(myevebday.getMonth() == 9);</p><p>  test(myevebday.getDay() == 30);</p><p>  test(mybday.toString() == "19511001");</p><p>  test(myevebday.toString() == "19510930");</p><empty-line/><p>  // Test duration</p><p>  Date d2(2003, 7, 4);</p><p>  Date::Duration dur = duration(mybday, d2);</p><p>  test(dur.years == 51);</p><p>  test(dur.months == 9);</p><p>  test(dur.days == 3);</p><empty-line/><p>  // Report results:</p><p>  cout &lt;&lt; "Passed: " &lt;&lt; nPass &lt;&lt; ", Failed: "</p><p>       &lt;&lt; nFail &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The word "final" above was quoted because this test can of course be more fully developed. For example we haven’t tested that long durations are handled correctly. To save space on the printed page we’ll stop here, but you get the idea. The full implementation for the <strong>Date</strong> class is available in the files <strong>Date.h</strong> and <strong>Date.cpp</strong> in the appendix and on the MindView website.<a l:href="#n21" type="note">[21]</a>[ ]</p></section><section><title><p>The TestSuite Framework</p></title><p>Some automated C++ unit test tools are available on the World Wide Web for download, such as <strong>CppUnit</strong>.<a l:href="#n22" type="note">[22]</a> These are well designed and implemented, but our purpose here is not only to present a test mechanism that is easy to use, but also easy to understand internally and even tweak if necessary. So, in the spirit of "TheSimplestThingThatCouldPossiblyWork," we have developed the <emphasis>TestSuite Framework</emphasis>, a namespace named <strong>TestSuite</strong> that contains two key classes: <strong>Test</strong> and <strong>Suite</strong><sup><strong>.</strong></sup></p><p>The <strong>Test</strong> class is an abstract class you derive from to define a test object. It keeps track of the number of passes and failures for you and displays the text of any test condition that fails. Your main task in defining a test is simply to override the <strong>run( )</strong> member function, which should in turn call the <strong>test_( )</strong> macro for each Boolean test condition you define<sup>.</sup></p><p>To define a test for the <strong>Date</strong> class using the framework, you can inherit from <strong>Test</strong> as shown in the following program:</p><p>//: C02:DateTest.h</p><p>#ifndef DATE_TEST_H</p><p>#define DATE_TEST_H</p><p>#include "Date.h"</p><p>#include "../TestSuite/Test.h"</p><empty-line/><p>class DateTest : public TestSuite::Test {</p><p>  Date mybday;</p><p>  Date today;</p><p>  Date myevebday;</p><p>public:</p><p>  DateTest() : mybday(1951, 10, 1), myevebday("19510930") {</p><p>  }</p><p>  void run() {</p><p>    testOps();</p><p>    testFunctions();</p><p>    testDuration();</p><p>  }</p><p>  void testOps() {</p><p>    test_(mybday &lt; today);</p><p>    test_(mybday &lt;= today);</p><p>    test_(mybday != today);</p><p>    test_(mybday == mybday);</p><p>    test_(mybday &gt;= mybday);</p><p>    test_(mybday &lt;= mybday);</p><p>    test_(myevebday &lt; mybday);</p><p>    test_(mybday &gt; myevebday);</p><p>    test_(mybday &gt;= myevebday);</p><p>    test_(mybday != myevebday);</p><p>  }</p><p>  void testFunctions() {</p><p>    test_(mybday.getYear() == 1951);</p><p>    test_(mybday.getMonth() == 10);</p><p>    test_(mybday.getDay() == 1);</p><p>    test_(myevebday.getYear() == 1951);</p><p>    test_(myevebday.getMonth() == 9);</p><p>    test_(myevebday.getDay() == 30);</p><p>    test_(mybday.toString() == "19511001");</p><p>    test_(myevebday.toString() == "19510930");</p><p>  }</p><p>  void testDuration() {</p><p>    Date d2(2003, 7, 4);</p><p>    Date::Duration dur = duration(mybday, d2);</p><p>    test_(dur.years == 51);</p><p>    test_(dur.months == 9);</p><p>    test_(dur.days == 3);</p><p>  }</p><p>};</p><p>#endif ///:~</p><empty-line/><p>Running the test is a simple matter of instantiating a <strong>DateTest</strong> object and calling its <strong>run( )</strong> member function<sup>.</sup></p><p>//: C02:DateTest.cpp</p><p>// Automated Testing (with a Framework)</p><p>//{L} Date ../TestSuite/Test</p><p>#include &lt;iostream&gt;</p><p>#include "DateTest.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  DateTest test;</p><p>  test.run();</p><p>  return test.report();</p><p>}</p><p>/* Output:</p><p>Test "DateTest":</p><p>        Passed: 21,      Failed: 0</p><p>*/ ///:~</p><empty-line/><p>The <strong>Test::report( )</strong> function displays the previous output and returns the number of failures, so it is suitable to use as a return value from <strong>main( )</strong><sup><strong>.</strong></sup></p><p>The <strong>Test</strong> class uses RTTI<a l:href="#n23" type="note">[23]</a> to get the name of your class (for example, <strong>DateTest</strong>) for the report. There is also a <strong>setStream( )</strong> member function if you want the test results sent to a file instead of to the standard output (the default). You’ll see the <strong>Test</strong> class implementation later in this chapter<sup>.</sup></p><p>The <strong>test_ ( )</strong> macro can extract the text of the Boolean condition that fails, along with its file name and line number.<a l:href="#n24" type="note">[24]</a> To see what happens when a failure occurs, you can introduce an intentional error in the code, say by reversing the condition in the first call to <strong>test_( )</strong> in <strong>DateTest::testOps( )</strong> in the previous example code. The output indicates exactly what test was in error and where it happened:<sup>.</sup></p><p>DateTest failure: (mybday &gt; today) , DateTest.h (line 31)</p><p>Test "DateTest":</p><p>        Passed: 20      Failed: 1</p><empty-line/><p>In addition to <strong>test_( )</strong>, the framework includes the functions <strong>succeed_( )</strong> and <strong>fail_( )</strong>, for cases in which a Boolean test won't do. These functions apply when the class you’re testing might throw exceptions. During testing, you want to arrange an input set that will cause the exception to occur to make sure it’s doing its job. If it doesn’t, it’s an error, in which case you call <strong>fail_( )</strong> explicitly to display a message and update the failure count. If it does throw the exception as expected, you call <strong>succeed_ ( )</strong> to update the success count<sup>.</sup></p><p>To illustrate, suppose we update the specification of the two non-default <strong>Date</strong> constructors to throw a <strong>DateError</strong> exception (a type nested inside <strong>Date</strong> and derived from <strong>std::logic_error</strong>) if the input parameters do not represent a valid date:<sup>.</sup></p><p>Date(const string&amp; s) throw(DateError);</p><p>Date(int year, int month, int day) throw(DateError);</p><empty-line/><p>The <strong>DateTest::run( )</strong> member function can now call the following function to test the exception handling:</p><p>  void testExceptions() {</p><p>    try {</p><p>      Date d(0,0,0);  // Invalid</p><p>      fail_("Invalid date undetected in Date int ctor");</p><p>    }</p><p>    catch (Date::DateError&amp;) {</p><p>      succeed_();</p><p>    }</p><p>    try {</p><p>      Date d("");  // Invalid</p><p>      fail_("Invalid date undetected in Date string ctor");</p><p>    }</p><p>    catch (Date::DateError&amp;) {</p><p>      succeed_();</p><p>    }</p><p>  }</p><empty-line/><p>In both cases, if an exception is not thrown, it is an error. Notice that you have to manually pass a message to <strong>fail_( )</strong>, since no Boolean expression is being evaluated<sup>.</sup></p></section><section><title><p>Test suites</p></title><p>Real projects usually contain many classes, so you need a way to group tests so that you can just push a single button to test the entire project.<a l:href="#n25" type="note">[25]</a> The <strong>Suite</strong> class allows you to collect tests into a functional unit. You derive <strong>Test</strong> objects to a <strong>Suite</strong> with the <strong>addTest( )</strong> member function, or you can swallow an entire existing suite with <strong>addSuite( )</strong>. We have a number of date-related classes to illustrate how to use a test suite. Here's an actual test run:<sup>.</sup></p><p>// Illustrates a suite of related tests</p><p>#include &lt;iostream&gt;</p><p>#include "suite.h"         // includes test.h</p><p>#include "JulianDateTest.h"</p><p>#include "JulianTimeTest.h"</p><p>#include "MonthInfoTest.h"</p><p>#include "DateTest.h"</p><p>#include "TimeTest.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>    Suite s("Date and Time Tests");</p><p>    s.addTest(new MonthInfoTest);</p><p>    s.addTest(new JulianDateTest);</p><p>    s.addTest(new JulianTimeTest);</p><p>    s.addTest(new DateTest);</p><p>    s.addTest(new TimeTest);</p><p>    s.run();</p><p>    long nFail = s.report();</p><p>    s.free();</p><p>    return nFail;</p><p>}</p><p>/* Output:</p><p>Suite "Date and Time Tests"</p><p>===========================</p><p>Test "MonthInfoTest":</p><p>   Passed: 18  Failed: 0</p><p>Test "JulianDateTest":</p><p>   Passed: 36  Failed: 0</p><p>Test "JulianTimeTest":</p><p>   Passed: 29  Failed: 0</p><p>Test "DateTest":</p><p>   Passed: 57  Failed: 0</p><p>Test "TimeTest":</p><p>   Passed: 84  Failed: 0</p><p>===========================</p><p>*/</p><empty-line/><p>Each of the five test files included as headers tests a unique date component. You must give the suite a name when you create it. The <strong>Suite::run( )</strong> member function calls <strong>Test::run( )</strong> for each of its contained tests. Much the same thing happens for <strong>Suite::report( )</strong>, except that it is possible to send the individual test reports to a destination stream that is different from that of the suite report. If the test passed to <strong>addSuite( )</strong> has a stream pointer assigned already, it keeps it. Otherwise, it gets its stream from the <strong>Suite</strong> object. (As with <strong>Test</strong>, there is a second argument to the suite constructor that defaults to <strong>std::cout</strong>.) The destructor for <strong>Suite</strong> does not automatically delete the contained <strong>Test</strong> pointers because they don’t have to reside on the heap; that’s the job of <strong>Suite::free( )</strong><sup><strong>.</strong></sup></p></section><section><title><p>The test framework code</p></title><p>The test framework code library is in a subdirectory called <strong>TestSuite</strong> in the code distribution available on the MindView website. To use it, include the search path for the <strong>TestSuite</strong> subdirectory in your header, link the object files, and include the <strong>TestSuite</strong> subdirectory in the library search path. Here is the header for <strong>Test.h</strong>:</p><p>//: TestSuite:Test.h</p><p>#ifndef TEST_H</p><p>#define TEST_H</p><p>#include &lt;string&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;cassert&gt;</p><p>using std::string;</p><p>using std::ostream;</p><p>using std::cout;</p><empty-line/><p>// The following have underscores because</p><p>// they are macros. For consistency,</p><p>// succeed_() also has an underscore.</p><empty-line/><p>#define test_(cond) \</p><p>  do_test(cond, #cond, __FILE__, __LINE__)</p><p>#define fail_(str) \</p><p>  do_fail(str, __FILE__, __LINE__)</p><empty-line/><p>namespace TestSuite {</p><empty-line/><p>class Test {</p><p>public:</p><p>  Test(ostream* osptr = &amp;cout);</p><p>  virtual ~Test(){}</p><p>  virtual void run() = 0;</p><p>  long getNumPassed() const;</p><p>  long getNumFailed() const;</p><p>  const ostream* getStream() const;</p><p>  void setStream(ostream* osptr);</p><p>  void succeed_();</p><p>  long report() const;</p><p>  virtual void reset();</p><p>protected:</p><p>  void do_test(bool cond, const string&amp; lbl,</p><p>    const char* fname, long lineno);</p><p>  void do_fail(const string&amp; lbl,</p><p>    const char* fname, long lineno);</p><p>private:</p><p>  ostream* osptr;</p><p>  long nPass;</p><p>  long nFail;</p><p>  // Disallowed:</p><p>  Test(const Test&amp;);</p><p>  Test&amp; operator=(const Test&amp;);</p><p>};</p><empty-line/><p>inline Test::Test(ostream* osptr) {</p><p>  this-&gt;osptr = osptr;</p><p>  nPass = nFail = 0;</p><p>}</p><empty-line/><p>inline long Test::getNumPassed() const {</p><p>  return nPass;</p><p>}</p><empty-line/><p>inline long Test::getNumFailed() const {</p><p>  return nFail;</p><p>}</p><empty-line/><p>inline const ostream* Test::getStream() const {</p><p>  return osptr;</p><p>}</p><empty-line/><p>inline void Test::setStream(ostream* osptr) {</p><p>  this-&gt;osptr = osptr;</p><p>}</p><empty-line/><p>inline void Test::succeed_() {</p><p>  ++nPass;</p><p>}</p><empty-line/><p>inline void Test::reset() {</p><p>  nPass = nFail = 0;</p><p>}</p><empty-line/><p>} // namespace TestSuite</p><p>#endif // TEST_H ///:~</p><empty-line/><p>There are three virtual functions in the <strong>Test</strong> class:</p><p>·         A virtual destructor</p><p>·         The function <strong>reset( )</strong></p><p>·         The pure virtual function <strong>run( )</strong></p><p>As explained in Volume 1, it is an error to delete a derived heap object through a base pointer unless the base class has a virtual destructor. Any class intended to be a base class (usually evidenced by the presence of at least one other virtual function) should have a virtual destructor. The default implementation of the <strong>Test::reset( )</strong> resets the success and failure counters to zero. You might want to override this function to reset the state of the data in your derived test object; just be sure to call <strong>Test::reset( )</strong> explicitly in your override so that the counters are reset. The <strong>Test::run( )</strong> member function is pure virtual, of course, since you are required to override it in your derived class<sup>.</sup></p><p>The <strong>test_( )</strong> and <strong>fail_( )</strong> macros can include file name and line number information available from the preprocessor. We originally omitted the trailing underscores in the names, but the original <strong>fail( )</strong> macro collided with <strong>ios::fail( )</strong>, causing all kinds of compiler errors<sup>.</sup></p><p>Here is the implementation of <strong>Test</strong>:</p><p>//: TestSuite:Test.cpp {O}</p><p>#include "Test.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;typeinfo&gt;  // Note: Visual C++ requires /GR</p><p>using namespace std;</p><p>using namespace TestSuite;</p><empty-line/><p>void Test::do_test(bool cond,</p><p>  const std::string&amp; lbl, const char* fname,</p><p>  long lineno) {</p><p>  if (!cond)</p><p>    do_fail(lbl, fname, lineno);</p><p>  else</p><p>    succeed_();</p><p>}</p><empty-line/><p>void Test::do_fail(const std::string&amp; lbl,</p><p>  const char* fname, long lineno) {</p><p>  ++nFail;</p><p>  if (osptr) {</p><p>    *osptr &lt;&lt; typeid(*this).name()</p><p>           &lt;&lt; "failure: (" &lt;&lt; lbl &lt;&lt; ") , "</p><p>           &lt;&lt; fname</p><p>           &lt;&lt; " (line " &lt;&lt; lineno &lt;&lt; ")\n";</p><p>  }</p><p>}</p><empty-line/><p>long Test::report() const {</p><p>  if (osptr) {</p><p>    *osptr &lt;&lt; "Test \"" &lt;&lt; typeid(*this).name()</p><p>           &lt;&lt; "\":\n\tPassed: " &lt;&lt; nPass</p><p>           &lt;&lt; "\tFailed: " &lt;&lt; nFail</p><p>           &lt;&lt; endl;</p><p>  }</p><p>  return nFail;</p><p>} ///:~</p><empty-line/><p>No rocket science here. The <strong>Test</strong> class just keeps track of the number of successes and failures as well as the stream where you want <strong>Test::report( )</strong> to display the results. The <strong>test_( )</strong> and <strong>fail_( )</strong> macros extract the current file name and line number information from the preprocessor and pass the file name to <strong>do_test( )</strong> and the line number to <strong>do_fail( )</strong>, which do the actual work of displaying a message and updating the appropriate counter. We can’t think of a good reason to allow copy and assignment of test objects, so we have disallowed these operations by making their prototypes private and omitting their respective function bodies<sup>.</sup></p><p>Here is the header file for <strong>Suite</strong>:<sup>.</sup></p><p>//: TestSuite:Suite.h</p><p>#ifndef SUITE_H</p><p>#define SUITE_H</p><p>#include "../TestSuite/Test.h"</p><p>#include &lt;vector&gt;</p><p>#include &lt;stdexcept&gt;</p><p>using std::vector;</p><p>using std::logic_error;</p><empty-line/><p>namespace TestSuite {</p><empty-line/><p>class TestSuiteError : public logic_error {</p><p>public:</p><p>  TestSuiteError(const string&amp; s = "")</p><p>    : logic_error(s) {}</p><p>};</p><empty-line/><p>class Suite {</p><p>public:</p><p>  Suite(const string&amp; name, ostream* osptr = &amp;cout);</p><p>  string getName() const;</p><p>  long getNumPassed() const;</p><p>  long getNumFailed() const;</p><p>  const ostream* getStream() const;</p><p>  void setStream(ostream* osptr);</p><p>  void addTest(Test* t) throw (TestSuiteError);</p><p>  void addSuite(const Suite&amp;);</p><p>  void run();  // Calls Test::run() repeatedly</p><p>  long report() const;</p><p>  void free();  // Deletes tests</p><p>private:</p><p>  string name;</p><p>  ostream* osptr;</p><p>  vector&lt;Test*&gt; tests;</p><p>  void reset();</p><p>  // Disallowed ops:</p><p>  Suite(const Suite&amp;);</p><p>  Suite&amp; operator=(const Suite&amp;);</p><p>};</p><empty-line/><p>inline</p><p>Suite::Suite(const string&amp; name, ostream* osptr)</p><p>   : name(name) {</p><p>  this-&gt;osptr = osptr;</p><p>}</p><empty-line/><p>inline string Suite::getName() const {</p><p>  return name;</p><p>}</p><empty-line/><p>inline const ostream* Suite::getStream() const {</p><p>  return osptr;</p><p>}</p><empty-line/><p>inline void Suite::setStream(ostream* osptr) {</p><p>  this-&gt;osptr = osptr;</p><p>}</p><empty-line/><p>} // namespace TestSuite</p><p>#endif // SUITE_H ///:~</p><empty-line/><p>The <strong>Suite</strong> class holds pointers to its <strong>Test</strong> objects in a vector. Notice the exception specification on the <strong>addTest( )</strong> member function. When you add a test to a suite, <strong>Suite::addTest( )</strong> verifies that the pointer you pass is not null; if it is null, it throws a <strong>TestSuiteError</strong> exception. Since this makes it impossible to add a null pointer to a suite, <strong>addSuite( )</strong> asserts this condition on each of its tests, as do the other functions that traverse the vector of tests (see the following implementation). Copy and assignment are disallowed as they are in the <strong>Test</strong> class<sup>.</sup></p><p>//: TestSuite:Suite.cpp {O}</p><p>#include "Suite.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;cassert&gt;</p><p>using namespace std;</p><p>using namespace TestSuite;</p><empty-line/><p>void Suite::addTest(Test* t) throw(TestSuiteError) {</p><p>  // Verify test is valid and has a stream:</p><p>  if (t == 0)</p><p>    throw TestSuiteError(</p><p>      "Null test in Suite::addTest");</p><p>  else if (osptr &amp;&amp; !t-&gt;getStream())</p><p>    t-&gt;setStream(osptr);</p><p>  tests.push_back(t);</p><p>  t-&gt;reset();</p><p>}</p><empty-line/><p>void Suite::addSuite(const Suite&amp; s) {</p><p>for (size_t i = 0; i &lt; s.tests.size(); ++i) {</p><p>  assert(tests[i]);</p><p>addTest(s.tests[i]);</p><p>  }</p><p>}</p><empty-line/><p>void Suite::free() {</p><p>  for (size_t i = 0; i &lt; tests.size(); ++i) {</p><p>    delete tests[i];</p><p>    tests[i] = 0;</p><p>  }</p><p>}</p><empty-line/><p>void Suite::run() {</p><p>  reset();</p><p>  for (size_t i = 0; i &lt; tests.size(); ++i) {</p><p>    assert(tests[i]);</p><p>    tests[i]-&gt;run();</p><p>  }</p><p>}</p><empty-line/><p>long Suite::report() const {</p><p>  if (osptr) {</p><p>    long totFail = 0;</p><p>    *osptr &lt;&lt; "Suite \"" &lt;&lt; name</p><p>             &lt;&lt; "\"\n=======";</p><p>    size_t i;</p><p>    for (i = 0; i &lt; name.size(); ++i)</p><p>      *osptr &lt;&lt; '=';</p><p>    *osptr &lt;&lt; "=\n";</p><p>    for (i = 0; i &lt; tests.size(); ++i) {</p><p>      assert(tests[i]);</p><p>      totFail += tests[i]-&gt;report();</p><p>    }</p><p>    *osptr &lt;&lt; "=======";</p><p>    for (i = 0; i &lt; name.size(); ++i)</p><p>      *osptr &lt;&lt; '=';</p><p>    *osptr &lt;&lt; "=\n";</p><p>    return totFail;</p><p>  }</p><p>  else</p><p>    return getNumFailed();</p><p>}</p><empty-line/><p>long Suite::getNumPassed() const {</p><p>  long totPass = 0;</p><p>  for (size_t i = 0; i &lt; tests.size(); ++i) {</p><p>    assert(tests[i]);</p><p>    totPass += tests[i]-&gt;getNumPassed();</p><p>  }</p><p>  return totPass;</p><p>}</p><empty-line/><p>long Suite::getNumFailed() const {</p><p>  long totFail = 0;</p><p>  for (size_t i = 0; i &lt; tests.size(); ++i) {</p><p>    assert(tests[i]);</p><p>    totFail += tests[i]-&gt;getNumFailed();</p><p>  }</p><p>  return totFail;</p><p>}</p><empty-line/><p>void Suite::reset() {</p><p>  for (size_t i = 0; i &lt; tests.size(); ++i) {</p><p>    assert(tests[i]);</p><p>    tests[i]-&gt;reset();</p><p>  }</p><p>} ///:~</p><empty-line/><p>We will be using the <strong>TestSuite</strong> framework wherever it applies throughout the rest of this book<sup>.</sup></p></section></section><section><title><p>Debugging techniques</p></title><section><p>The best debugging habit to get into is to use assertions as explained in the beginning of this chapter; by doing so you’ll be more likely to find logic errors before they cause real trouble. This section contains some other tips and techniques that might help during debugging<sup>.</sup></p></section><section><title><p>Trace macros</p></title><p>Sometimes it’s helpful to print the code of each statement as it is executed, either to <strong>cout</strong> or to a trace file. Here’s a preprocessor macro to accomplish this:<sup>.</sup></p><p>#define TRACE(ARG) cout &lt;&lt; #ARG &lt;&lt; endl; ARG</p><empty-line/><p>Now you can go through and surround the statements you trace with this macro. Of course, it can introduce problems. For example, if you take the statement:<sup>.</sup></p><p>for(int i = 0; i &lt; 100; i++)</p><p>  cout &lt;&lt; i &lt;&lt; endl;</p><empty-line/><p>and put both lines inside <strong>TRACE( )</strong> macros, you get this:</p><p>TRACE(for(int i = 0; i &lt; 100; i++))</p><p>TRACE(  cout &lt;&lt; i &lt;&lt; endl;)</p><empty-line/><p>which expands to this:</p><p>cout &lt;&lt; "for(int i = 0; i &lt; 100; i++)" &lt;&lt; endl;</p><p>for(int i = 0; i &lt; 100; i++)</p><p>  cout &lt;&lt; "cout &lt;&lt; i &lt;&lt; endl;" &lt;&lt; endl;</p><p>cout &lt;&lt; i &lt;&lt; endl;</p><empty-line/><p>which isn’t exactly what you want. Thus, you must use this technique carefully<sup>.</sup></p><p>The following is a variation on the <strong>TRACE( )</strong> macro:</p><p>#define D(a) cout &lt;&lt; #a "=[" &lt;&lt; a &lt;&lt; "]" &lt;&lt; '\n';</p><empty-line/><p>If you want to display an expression, you simply put it inside a call to <strong>D( ).</strong> The expression is displayed, followed by its value (assuming there’s an overloaded operator <strong>&lt;&lt;</strong> for the result type). For example, you can say <strong>D(a + b)</strong>. Thus, you can use this macro any time you want to test an intermediate value to make sure things are okay<sup>.</sup></p><p>Of course, these two macros are actually just the two most fundamental things you do with a debugger: trace through the code execution and display values. A good debugger is an excellent productivity tool, but sometimes debuggers are not available, or it’s not convenient to use them. These techniques always work, regardless of the situation<sup>.</sup></p></section><section><title><p>Trace file</p></title><p>DISCLAIMER: This section and the next contain code which is officially unsanctioned by the C++ standard. In particular, we redefine <strong>cout</strong> and <strong>new</strong> via macros, which can cause surprising results if you’re not careful. Our examples work on all the compilers we use, however, and provide useful information. This is the only place in this book where we will depart from the sanctity of standard-compliant coding practice. Use at your own risk!</p><p>The following code allows you to easily create a trace file and send all the output that would normally go to <strong>cout</strong> into the file. All you have to do is <strong>#define</strong> TRACEON and include the header file (of course, it’s fairly easy just to write the two key lines right into your file):<sup>.</sup></p><p>//: C03:Trace.h</p><p>// Creating a trace file</p><p>#ifndef TRACE_H</p><p>#define TRACE_H</p><p>#include &lt;fstream&gt;</p><empty-line/><p>#ifdef TRACEON</p><p>ofstream TRACEFILE__("TRACE.OUT");</p><p>#define cout TRACEFILE__</p><p>#endif</p><empty-line/><p>#endif // TRACE_H ///:~</p><empty-line/><empty-line/><p>Here’s a simple test of the previous file:</p><p>//: C03:Tracetst.cpp</p><p>// Test of trace.h</p><p>#include "../require.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;fstream&gt;</p><p>using namespace std;</p><empty-line/><p>#define TRACEON</p><p>#include "Trace.h"</p><empty-line/><p>int main() {</p><p>  ifstream f("Tracetst.cpp");</p><p>  assure(f, "Tracetst.cpp");</p><p>  cout &lt;&lt; f.rdbuf(); // Dumps file contents to file</p><p>} ///:~</p><empty-line/><empty-line/></section><section><title><p>Finding memory leaks</p></title><section><p>The following straightforward debugging techniques are explained Volume 1.</p><p>1.       For array bounds checking, use the <strong>Array</strong> template in <strong>C16:Array3.cpp</strong> of Volume 1 for all arrays. You can turn off the checking and increase efficiency when you’re ready to ship. (This doesn’t deal with the case of taking a pointer to an array, though—perhaps that could be made into a template somehow as well)<sup>.</sup></p><p>2.      Check for non-virtual destructors in base classes<sup>.</sup></p></section><section><section><title><p>Tracking new/delete and malloc/free</p></title><p>Common problems with memory allocation include mistakenly calling <strong>delete</strong> for memory not on the free store, deleting the free store more than once, and, most often, forgetting to delete such a pointer at all. This section discusses a system that can help you track down these kinds of problems.</p><p>As an <emphasis>additional disclaimer</emphasis> beyond that of the preceding section: because of the way we overload <strong>new</strong>, the following technique may not work on all platforms, and will only work for programs that do not call the <emphasis>function</emphasis><strong>operator new( )</strong> explicitly. We have been quite careful in this book to only present code that fully conforms to the C++ standard, but in this one instance we’re making an exception for the following reasons:</p><p>             1.             Even though it’s technically illegal, it works on many compilers.<a l:href="#n26" type="note">[26]</a></p><p>             2.             We illustrate some useful thinking along the way.</p><empty-line/><p>To use the memory checking system, you simply include the header file <strong>MemCheck.h</strong>, link the <strong>MemCheck.obj</strong> file into your application, so that all the calls to <strong>new</strong> and <strong>delete</strong> are intercepted, and call the macro <strong>MEM_ON( )</strong> (explained later in this section) to initiate memory tracing. A trace of all allocations and deallocations is printed to the standard output (via <strong>stdout</strong>). When you use this system, all calls to <strong>new</strong> store information about the file and line where they were called. This is accomplished by using the <emphasis>placement syntax</emphasis> for <strong>operator new</strong>.<a l:href="#n27" type="note">[27]</a> Although you typically use the placement syntax when you need to place objects at a specific point in memory, it also allows you to create an <strong>operator new( )</strong> with any number of arguments. This is used to advantage in the following example to store the results of the <strong>__FILE__</strong> and <strong>__LINE__</strong> macros whenever <strong>new</strong> is called:<sup>.</sup></p><p>//: C02:MemCheck.h</p><p>#ifndef MEMCHECK_H</p><p>#define MEMCHECK_H</p><p>#include &lt;cstddef&gt;  // for size_t</p><empty-line/><p>// Hijack the new operator (both scalar and array versions)</p><p>void* operator new(std::size_t, const char*, long);</p><p>void* operator new[](std::size_t, const char*, long);</p><p>#define new new (__FILE__, __LINE__)</p><empty-line/><p>extern bool traceFlag;</p><p>#define TRACE_ON() traceFlag = true</p><p>#define TRACE_OFF() traceFlag = false</p><empty-line/><p>extern bool activeFlag;</p><p>#define MEM_ON() activeFlag = true</p><p>#define MEM_OFF() activeFlag = false</p><empty-line/><p>#endif</p><p>///:~</p><empty-line/><p>It is important that you include this file in any source file in which you want to track free store activity, but include it <emphasis>last</emphasis> (after your other <strong>#include</strong> directives). Most headers in the standard library are templates, and since most compilers use the <emphasis>inclusion model</emphasis> of template compilation (meaning all source code is in the headers), the macro that replaces <strong>new</strong> in <strong>MemCheck.h</strong> would usurp all instances of the <strong>new</strong> operator in the library source code (and would likely result in compile errors). Besides, you are only interested in tracking your own memory errors, not the library’s<sup>.</sup></p><p>In the following file, which contains the memory tracking implementation, everything is done with C standard I/O rather than with C++ iostreams. It shouldn’t make a difference, really, since we’re not interfering with iostreams’ use of the free store, but it’s safer to not take a chance. (Besides, we tried it. Some compilers complained, but all compilers were happy with the <strong>&lt;stdio&gt;</strong> version.)<sup>.</sup></p><p>//: C02:MemCheck.cpp {O}</p><p>#include &lt;cstdio&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;cassert&gt;</p><p>using namespace std;</p><p>#undef new</p><empty-line/><p>// Global flags set by macros in MemCheck.h</p><p>bool traceFlag = true;</p><p>bool activeFlag = false;</p><empty-line/><p>namespace {</p><empty-line/><p>// Memory map entry type</p><p>struct Info {</p><p>  void* ptr;</p><p>  const char* file;</p><p>  long line;</p><p>};</p><empty-line/><p>// Memory map data</p><p>const size_t MAXPTRS = 10000u;</p><p>Info memMap[MAXPTRS];</p><p>size_t nptrs = 0;</p><empty-line/><p>// Searches the map for an address</p><p>int findPtr(void* p) {</p><p>  for (int i = 0; i &lt; nptrs; ++i)</p><p>    if (memMap[i].ptr == p)</p><p>      return i;</p><p>  return -1;</p><p>}</p><empty-line/><p>void delPtr(void* p) {</p><p>  int pos = findPtr(p);</p><p>  assert(p &gt;= 0);</p><p>  // Remove pointer from map</p><p>  for (size_t i = pos; i &lt; nptrs-1; ++i)</p><p>    memMap[i] = memMap[i+1];</p><p>  --nptrs;</p><p>}</p><empty-line/><p>// Dummy type for static destructor</p><p>struct Sentinel {</p><p>  ~Sentinel() {</p><p>    if (nptrs &gt; 0) {</p><p>      printf("Leaked memory at:\n");</p><p>      for (size_t i = 0; i &lt; nptrs; ++i)</p><p>        printf("\t%p (file: %s, line %ld)\n",</p><p>          memMap[i].ptr, memMap[i].file, memMap[i].line);</p><p>    }</p><p>    else</p><p>      printf("No user memory leaks!\n");</p><p>  }</p><p>};</p><empty-line/><p>// Static dummy object</p><p>Sentinel s;</p><empty-line/><p>} // End anonymous namespace</p><empty-line/><p>// Overload scalar new</p><p>void* operator new(size_t siz, const char* file,</p><p>  long line) {</p><p>  void* p = malloc(siz);</p><p>  if (activeFlag) {</p><p>    if (nptrs == MAXPTRS) {</p><p>      printf("memory map too small (increase MAXPTRS)\n");</p><p>      exit(1);</p><p>    }</p><p>    memMap[nptrs].ptr = p;</p><p>    memMap[nptrs].file = file;</p><p>    memMap[nptrs].line = line;</p><p>    ++nptrs;</p><p>  }</p><p>  if (traceFlag) {</p><p>    printf("Allocated %u bytes at address %p ", siz, p);</p><p>    printf("(file: %s, line: %ld)\n", file, line);</p><p>  }</p><p>  return p;</p><p>}</p><empty-line/><p>// Overload array new</p><p>void* operator new[](size_t siz, const char* file,</p><p>  long line) {</p><p>  return operator new(siz, file, line);</p><p>}</p><empty-line/><p>// Override scalar delete</p><p>void operator delete(void* p) {</p><p>  if (findPtr(p) &gt;= 0) {</p><p>    free(p);</p><p>    assert(nptrs &gt; 0);</p><p>    delPtr(p);</p><p>    if (traceFlag)</p><p>      printf("Deleted memory at address %p\n", p);</p><p>  }</p><p>  else if (!p &amp;&amp; activeFlag)</p><p>    printf("Attempt to delete unknown pointer: %p\n", p);</p><p>}</p><empty-line/><p>// Override array delete</p><p>void operator delete[](void* p) {</p><p>  operator delete(p);</p><p>} ///:~</p><empty-line/><p>The Boolean flags <strong>traceFlag</strong> and <strong>activeFlag</strong> are global, so they can be modified in your code by the macros <strong>TRACE_ON( )</strong>, <strong>TRACE_OFF( )</strong>, <strong>MEM_ON( )</strong>, and <strong>MEM_OFF( )</strong>. In general, enclose all the code in your <strong>main( )</strong> within a <strong>MEM_ON( )</strong>-<strong>MEM_OFF( )</strong> pair so that memory is always tracked. Tracing, which echoes the activity of the replacement functions for <strong>operator new( )</strong> and <strong>operator delete( )</strong>, is on by default, but you can turn it off with <strong>TRACE_OFF( )</strong>. In any case, the final results are always printed (see the test runs later in this chapter).</p><p>The <strong>MemCheck</strong> facility tracks memory by keeping all addresses allocated by <strong>operator new( )</strong> in an array of <strong>Info</strong> structures, which also holds the file name and line number where the call to <strong>new</strong> occurred. As much information as possible is kept inside the anonymous namespace so as not to collide with any names you might have placed in the global namespace. The <strong>Sentinel</strong> class exists solely to have a static object’s destructor called as the program shuts down. This destructor inspects <strong>memMap</strong> to see if any pointers are waiting to be deleted (in which case you have a memory leak)<sup>.</sup></p><p>Our <strong>operator new( )</strong> uses <strong>malloc( )</strong> to get memory, and then adds the pointer and its associated file information to <strong>memMap</strong>. The <strong>operator delete( )</strong> function undoes all that work by calling <strong>free( )</strong> and decrementing <strong>nptrs</strong>, but first it checks to see if the pointer in question is in the map in the first place. If it isn’t, either you’re trying to delete an address that isn’t on the free store, or you’re trying to delete one that’s already been deleted and therefore previously removed from the map. The <strong>activeFlag</strong> variable is important here because we don’t want to process any deallocations from any system shutdown activity. By calling <strong>MEM_OFF( )</strong> at the end of your code, <strong>activeFlag</strong> will be set to <strong>false</strong>, and such subsequent calls to <strong>delete</strong> will be ignored. (Of course, that’s bad in a real program, but as we said earlier, our purpose here is to find <emphasis>your</emphasis> leaks; we’re not debugging the library.) For simplicity, we forward all work for array <strong>new</strong> and <strong>delete</strong> to their scalar counterparts<sup>.</sup></p><p>The following is a simple test using the <strong>MemCheck</strong> facility.</p><p>//: C02:MemTest.cpp</p><p>//{L} MemCheck</p><p>// Test of MemCheck system</p><p>#include &lt;iostream&gt;</p><p>#include &lt;vector&gt;</p><p>#include &lt;cstring&gt;</p><p>#include "MemCheck.h"   // Must appear last!</p><p>using namespace std;</p><empty-line/><p>class Foo {</p><p>  char* s;</p><p>public:</p><p>  Foo(const char*s ) {</p><p>    this-&gt;s = new char[strlen(s) + 1];</p><p>    strcpy(this-&gt;s, s);</p><p>  }</p><p>  ~Foo() {</p><p>    delete [] s;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  MEM_ON();</p><p>  cout &lt;&lt; "hello\n";</p><p>  int* p = new int;</p><p>  delete p;</p><p>  int* q = new int[3];</p><p>  delete [] q;</p><p>  int* r;</p><p>  delete r;</p><p>  vector&lt;int&gt; v;</p><p>  v.push_back(1);</p><p>  Foo s("goodbye");</p><p>  MEM_OFF();</p><p>} ///:~</p><empty-line/><p>This example verifies that you can use <strong>MemCheck</strong> in the presence of streams, standard containers, and classes that allocate memory in constructors. The pointers <strong>p</strong> and <strong>q</strong> are allocated and deallocated without any problem, but <strong>r</strong> is not a valid heap pointer, so the output indicates the error as an attempt to delete an unknown pointer<sup>.</sup></p><p>hello</p><p>Allocated 4 bytes at address 0xa010778 (file: memtest.cpp, line: 25)</p><p>Deleted memory at address 0xa010778</p><p>Allocated 12 bytes at address 0xa010778 (file: memtest.cpp, line: 27)</p><p>Deleted memory at address 0xa010778</p><p>Attempt to delete unknown pointer: 0x1</p><p>Allocated 8 bytes at address 0xa0108c0 (file: memtest.cpp, line: 14)</p><p>Deleted memory at address 0xa0108c0</p><p>No user memory leaks!</p><empty-line/><p>Because of the call to <strong>MEM_OFF( )</strong>, no subsequent calls to <strong>operator delete( )</strong> by <strong>vector</strong> or <strong>ostream</strong> are processed. You still might get some calls to <strong>delete</strong> from reallocations performed by the containers<sup>.</sup></p><p>If you call <strong>TRACE_OFF( )</strong> at the beginning of the program, the output is as follows:</p><p>hello</p><p>Attempt to delete unknown pointer: 0x1</p><p>No user memory leaks!<sup>.</sup></p><empty-line/></section></section></section></section><section><title><p>Summary</p></title><p>Much of the headache of software engineering can be avoided by being deliberate about what you’re doing. You’ve probably been using mental assertions as you’ve crafted your loops and functions anyway, even if you haven’t routinely used the <strong>assert( )</strong> macro. If you’ll use <strong>assert( )</strong>, you’ll find logic errors sooner and end up with more readable code as well. Remember to only use assertions for invariants, though, and not for runtime error handling.</p><p>Nothing will give you more peace of mind than thoroughly tested code. If it’s been a hassle for you in the past, use an automated framework, such as the one we’ve presented here, to integrate routine testing into your daily work. You (and your users!) will be glad you did.</p></section><section><title><p>Exercises</p></title><p>             1.             Write a test program using the <strong>TestSuite</strong> Framework for the standard vector class that thoroughly tests the following member functions with a vector of integers: <strong>push_back( )</strong> (appends an element to the end of the vector), <strong>front( )</strong> (returns the first element in the vector), <strong>back( )</strong> (returns the last element in the vector), <strong>pop_back( )</strong> (removes the last element without returning it), <strong>at( )</strong> (returns the element in a specified index position), and <strong>size( )</strong> (returns the number of elements). Be sure to verify that <strong>vector::at( )</strong> throws a <strong>std::out_of_range</strong> exception if the supplied index is out of range.</p><p>         14.             Suppose you are asked to develop a class named <strong>Rational</strong> that supports rational numbers (fractions). The fraction in a <strong>Rational</strong> object should always be stored in lowest terms, and a denominator of zero is an error. Here is a sample interface for such a <strong>Rational</strong> class:</p><p>class Rational {</p><p>public:</p><p>   Rational(int numerator = 0, int denominator = 1);</p><p>   Rational operator-() const;</p><p>   friend Rational operator+(const Rational&amp;,</p><p>              const Rational&amp;);</p><p>   friend Rational operator-(const Rational&amp;,</p><p>              const Rational&amp;);</p><p>   friend Rational operator*(const Rational&amp;,</p><p>              const Rational&amp;);</p><p>   friend Rational operator/(const Rational&amp;,</p><p>              const Rational&amp;);</p><p>   friend ostream&amp; operator&lt;&lt;(ostream&amp;,</p><p>               const Rational&amp;);</p><p>   friend istream&amp; operator&gt;&gt;(istream&amp;, Rational&amp;);</p><p>   Rational&amp; operator+=(const Rational&amp;);</p><p>   Rational&amp; operator-=(const Rational&amp;);</p><p>   Rational&amp; operator*=(const Rational&amp;);</p><p>   Rational&amp; operator/=(const Rational&amp;);</p><p>   friend bool operator&lt;(const Rational&amp;,</p><p>          const Rational&amp;);</p><p>   friend bool operator&gt;(const Rational&amp;,</p><p>          const Rational&amp;);</p><p>   friend bool operator&lt;=(const Rational&amp;,</p><p>                          const Rational&amp;);</p><p>   friend bool operator&gt;=(const Rational&amp;,</p><p>           const Rational&amp;);</p><p>   friend bool operator==(const Rational&amp;,</p><p>           const Rational&amp;);</p><p>   friend bool operator!=(const Rational&amp;,</p><p>           const Rational&amp;);</p><p>};</p><empty-line/><p>Write a complete specification for this class, including pre-conditions, post-conditions, and exception specifications.</p><p>         15.             Write a test using the <strong>TestSuite</strong> framework that thoroughly tests all the specifications from the previous exercise, including testing exceptions.</p><p>         16.             Implement the <strong>Rational</strong> class so that all the tests from the previous exercise pass. Use assertions only for invariants.</p><p>         17.             The file <strong>BuggedSearch.cpp</strong> below contains a binary search function that searches the range <strong>[beg, end)</strong> for <strong>what</strong>. There are some bugs in the algorithm. Use the trace techniques from this chapter to debug the search function.</p><empty-line/><p>// BuggedSearch.cpp</p><p>#include "../TestSuite/Test.h"</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;cassert&gt;</p><p>#include &lt;fstream&gt;</p><p>using namespace std;</p><empty-line/><p>// This function is only one with bugs</p><p>int* binarySearch(int* beg, int* end, int what) {</p><p>  while(end - beg != 1) {</p><p>    if(*beg == what) return beg;</p><p>    int mid = (end - beg) / 2;</p><p>    if(what &lt;= beg[mid]) end = beg + mid;</p><p>    else beg = beg + mid;</p><p>  }</p><p>  return 0;</p><p>}</p><p>class BinarySearchTest : public TestSuite::Test {</p><p>  enum { sz = 10 };</p><p>  int* data;</p><p>  int max; //Track largest number</p><p>  int current; // Current non-contained number</p><p>// Used in notContained()</p><p>  // Find the next number not contained in the array</p><p>  int notContained() {</p><p>    while(data[current] + 1 == data[current + 1])</p><p>     current++;</p><p>    if(current &gt;= sz) return max + 1;</p><p>    int retValue = data[current++] + 1;</p><p>    return retValue;</p><p>  }</p><p>  void setData() {</p><p>    data = new int[sz];</p><p>    assert(!max);</p><p>    // Input values with increments of one.  Leave</p><p>    // out some values on both odd and even indexes.</p><p>    for(int i = 0; i &lt; sz;</p><p>        rand() % 2 == 0 ? max += 1 : max += 2)</p><p>      data[i++] = max;</p><p>  }</p><p>  void testInBound() {</p><p>    // Test locations both odd and even</p><p>    // not contained and contained</p><p>    for(int i = sz; --i &gt;=0;)</p><p>      test_(binarySearch(data, data + sz, data[i]));</p><p>    for(int i = notContained(); i &lt; max;</p><p>                   i = notContained())</p><p>      test_(!binarySearch(data, data + sz, i));</p><p>  }</p><p>  void testOutBounds() {</p><p>    // Test lower values</p><p>    for(int i = data[0]; --i &gt; data[0] - 100;)</p><p>      test_(!binarySearch(data, data + sz, i));</p><p>    // Test higher values</p><p>    for(int i = data[sz - 1];</p><p>        ++i &lt; data[sz -1] + 100;)</p><p>      test_(!binarySearch(data, data + sz, i));</p><p>  }</p><p>public:</p><p>  BinarySearchTest() {</p><p>    max = current = 0;</p><p>  }</p><p>  void run() {</p><p>    srand(time(0));</p><p>    setData();</p><p>    testInBound();</p><p>    testOutBounds();</p><p>    delete [] data;</p><p>  }</p><p>};</p><p>int main() {</p><p>  BinarySearchTest t;</p><p>  t.run();</p><p>  return t.report();</p><p>}</p></section></section></section><section><title><p>Part 2.The Standard C++ Library</p></title><section><p>Standard C++ not only incorporates all the Standard C libraries (with small additions and changes to support type safety), it also adds libraries of its own. These libraries are far more powerful than those in Standard C; the leverage you get from them is analogous to the leverage you get from changing from C to C++.</p><p>This part of the book gives you an in-depth introduction to key portions of the Standard C++ library<sup>.</sup></p><p>The most complete and also the most obscure reference to the full libraries is the Standard itself. Bjarne Stroustrup’s <emphasis>The C++ Programming Language, Third Edition </emphasis>(Addison-Wesley, 2000) remains a reliable reference for both the language and the library. The most celebrated library-only reference is <emphasis>The C++ Standard Library: A Tutorial and Reference</emphasis>, by Nicolai Josuttis (Addison-Wesley, 1999). The goal of the chapters in this part of the book is to provide you with an encyclopedia of descriptions and examples so that you’ll have a good starting point for solving any problem that requires the use of the Standard libraries. However, some techniques and topics are rarely used and are not covered here. If you can’t find it in these chapters, reach for the other two books; this book is not intended to replace those books but rather to complement them. In particular, we hope that after going through the material in the following chapters you’ll have a much easier time understanding those books<sup>.</sup></p><p>You will notice that these chapters do not contain exhaustive documentation describing every function and class in the Standard C++ library. We’ve left the full descriptions to others; in particular to P.J. Plauger’s <emphasis>Dinkumware C/C++ Library Reference</emphasis> at http://www.dinkumware.com. This is an excellent online source of standard library documentation in HTML format that you can keep resident on your computer and view with a Web browser whenever you need to look up something. . You can view this online and purchase it for local viewing. It contains complete reference pages for the both the C and C++ libraries (so it’s good to use for all your Standard C/C++ programming questions). Electronic documentation is effective not only because you can always have it with you, but also because you can do an electronic search for what you want<sup>.</sup></p><p>When you’re actively programming, these resources should adequately satisfy your reference needs (and you can use them to look up anything in this chapter that isn’t clear to you). Appendix A lists additional references<sup>.</sup></p><p>The first chapter in this section introduces the Standard C++ <strong>string</strong> class, which is a powerful tool that simplifies most of the text-processing chores you might have. The <strong>string</strong> class might be the most thorough string manipulation tool you’ve ever seen. Chances are, anything you’ve done to character strings with lines of code in C can be done with a member function call in the string class<sup>.</sup></p><p>Chapter 4 covers the <strong>iostreams</strong> library, which contains classes for processing input and output with files, string targets, and the system console<sup>.</sup></p><p>Although Chapter 5, "Templates in Depth," is not explicitly a library chapter, it is necessary preparation for the two that follow. In Chapter 6 we examine the generic algorithms offered by the Standard C++ library. Because they are implemented with templates, these algorithms can be applied to any <emphasis>sequence</emphasis> of objects. Chapter 7 covers the standard containers and their associated iterators. We cover algorithms first because they can be fully explored by using only arrays and the vector container (which we have been using since early in Volume 1). It is also natural to use the standard algorithms in connection with containers, so it’s a good idea to be familiar with the algorithm before studying the containers.</p><empty-line/><p>[ ]</p></section><section><title><p>3: Strings in depth</p></title><section><p>One of the biggest time-wasters in C is using character arrays for string processing: keeping track of the difference between static quoted strings and arrays created on the stack and the heap, and the fact that sometimes you’re passing around a <strong>char*</strong> and sometimes you must copy the whole array.</p><p>Especially because string manipulation is so common, character arrays are a great source of misunderstandings and bugs. Despite this, creating string classes remained a common exercise for beginning C++ programmers for many years. The Standard C++ library <strong>string</strong> class solves the problem of character array manipulation once and for all, keeping track of memory even during assignments and copy-constructions. You simply don’t need to think about it<sup>.</sup></p><p>This chapter examines the Standard C++ <strong>string</strong> class, beginning with a look at what constitutes a C++ string and how the C++ version differs from a traditional C character array. You’ll learn about operations and manipulations using <strong>string</strong> objects, and you’ll see how C++ <strong>string</strong>s accommodate variation in character sets and string data conversion.<a l:href="#n28" type="note">[28]</a></p><p>Handling text is perhaps one of the oldest of all programming applications, so it’s not surprising that the C++ <strong>string</strong> draws heavily on the ideas and terminology that have long been used for this purpose in C and other languages. As you begin to acquaint yourself with C++ <strong>string</strong>s, this fact should be reassuring. No matter which programming idiom you choose, there are really only about three things you want to do with a <strong>string</strong>:</p><p>·         Create or modify the sequence of characters stored in the <strong>string</strong>.</p><p>·         Detect the presence or absence of elements within the <strong>string</strong>.</p><p>·         Translate between various schemes for representing <strong>string</strong> characters<sup>.</sup></p><p>You’ll see how each of these jobs is accomplished using C++ <strong>string</strong> objects<sup>.</sup></p></section><section><title><p>What’s in a string?</p></title><p>In C, a string is simply an array of characters that always includes a binary zero (often called the <emphasis>null terminator</emphasis>) as its final array element. There are significant differences between C++ <strong>string</strong>s and their C progenitors. First, and most important, C++ strings hide the physical representation of the sequence of characters they contain. You don’t have to be concerned at all about array dimensions or null terminators. A <strong>string</strong> also contains certain "housekeeping" information about the size and storage location of its data. Specifically, a C++ <strong>string</strong> object knows its starting location in memory, its content, its length in characters, and the length in characters to which it can grow before the <strong>string</strong> object must resize its internal data buffer. C++ strings therefore greatly reduce the likelihood of making three of the most common and destructive C programming errors: overwriting array bounds, trying to access arrays through uninitialized or incorrectly valued pointers, and leaving pointers "dangling" after an array ceases to occupy the storage that was once allocated to it<sup>.</sup></p><p>The exact implementation of memory layout for the string class is not defined by the C++ Standard. This architecture is intended to be flexible enough to allow differing implementations by compiler vendors, yet guarantee predictable behavior for users. In particular, the exact conditions under which storage is allocated to hold data for a string object are not defined. String allocation rules were formulated to allow but not require a reference-counted implementation, but whether or not the implementation uses reference counting, the semantics must be the same. To put this a bit differently, in C, every <strong>char</strong> array occupies a unique physical region of memory. In C++, individual <strong>string</strong> objects may or may not occupy unique physical regions of memory, but if reference counting is used to avoid storing duplicate copies of data, the individual objects must look and act as though they do exclusively own unique regions of storage. For example:<sup>.</sup></p><p>//: C03:StringStorage.cpp</p><p>//{L} ../TestSuite/Test</p><p>#include &lt;string&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "../TestSuite/Test.h"</p><p>using namespace std;</p><empty-line/><p>class StringStorageTest : public TestSuite::Test {</p><p>public:</p><p>  void run() {</p><p>    string s1("12345");</p><p>    // This may copy the first to the second or</p><p>    // use reference counting to simulate a copy</p><p>    string s2 = s1;</p><p>    test_(s1 == s2);</p><p>    // Either way, this statement must ONLY modify s1</p><p>    s1[0] = '6';</p><p>    cout &lt;&lt; "s1 = " &lt;&lt; s1 &lt;&lt; endl;</p><p>    cout &lt;&lt; "s2 = " &lt;&lt; s2 &lt;&lt; endl;</p><p>    test_(s1 != s2);</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  StringStorageTest t;</p><p>  t.run();</p><p>  return t.report();</p><p>} ///:~</p><empty-line/><p>An implementation that only makes unique copies when a string is modified is said to use a <emphasis>copy-on-write</emphasis> strategy. This approach saves time and space when strings are used only as value parameters or in other read-only situations.</p><p>Whether a library implementation uses reference counting or not should be transparent to users of the <strong>string</strong> class. Unfortunately, this is not always the case. In multithreaded programs, it is practically impossible to use a reference-counting implementation safely.<a l:href="#n29" type="note">[29]</a></p></section><section><title><p>Creating and initializing C++ strings</p></title><p>Creating and initializing strings is a straightforward proposition and fairly flexible. In the <strong>SmallString.cpp</strong> example in this section, the first <strong>string</strong>, <strong>imBlank</strong>, is declared but contains no initial value. Unlike a C <strong>char</strong> array, which would contain a random and meaningless bit pattern until initialization, <strong>imBlank</strong> does contain meaningful information. This <strong>string</strong> object is initialized to hold "no characters" and can properly report its zero length and absence of data elements through the use of class member functions.</p><p>The next string, <strong>heyMom</strong>, is initialized by the literal argument "Where are my socks?" This form of initialization uses a quoted character array as a parameter to the <strong>string</strong> constructor. By contrast, <strong>standardReply</strong> is simply initialized with an assignment. The last string of the group, <strong>useThisOneAgain</strong>, is initialized using an existing C++ <strong>string</strong> object. Put another way, this example illustrates that <strong>string</strong> objects let you do the following:<sup>.</sup></p><p>·         Create an empty <strong>string</strong> and defer initializing it with character data.</p><p>·         Initialize a <strong>string</strong> by passing a literal, quoted character array as an argument to the constructor.</p><p>·         Initialize a <strong>string</strong> using the equal sign (<strong>=</strong>).</p><p>·         Use one <strong>string</strong> to initialize another<sup>.</sup></p><p>//: C03:SmallString.cpp</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  string imBlank;</p><p>  string heyMom("Where are my socks?");</p><p>  string standardReply = "Beamed into deep "</p><p>    "space on wide angle dispersion?";</p><p>  string useThisOneAgain(standardReply);</p><p>} ///:~</p><empty-line/><p>These are the simplest forms of <strong>string</strong> initialization, but variations offer more flexibility and control. You can do the following:</p><p>&#xE008; Use a portion of either a C <strong>char</strong> array or a C++ <strong>string</strong>. </p><p>&#xE008; Combine different sources of initialization data using <strong>operator+</strong>. </p><p>&#xE008; Use the <strong>string</strong> object’s <strong>substr( )</strong> member function to create a substring<sup>.</sup></p><p>Here’s a program that illustrates these features.</p><p>//: C03:SmallString2.cpp</p><p>#include &lt;string&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  string s1</p><p>    ("What is the sound of one clam napping?");</p><p>  string s2</p><p>    ("Anything worth doing is worth overdoing.");</p><p>  string s3("I saw Elvis in a UFO");</p><p>  // Copy the first 8 chars</p><p>  string s4(s1, 0, 8);</p><p>  cout &lt;&lt; s4 &lt;&lt; endl;</p><p>  // Copy 6 chars from the middle of the source</p><p>  string s5(s2, 15, 6);</p><p>  cout &lt;&lt; s5 &lt;&lt; endl;</p><p>  // Copy from middle to end</p><p>  string s6(s3, 6, 15);</p><p>  cout &lt;&lt; s6 &lt;&lt; endl;</p><p>  // Copy all sorts of stuff</p><p>  string quoteMe = s4 + "that" +</p><p>  // substr() copies 10 chars at element 20</p><p>  s1.substr(20, 10) + s5 +</p><p>  // substr() copies up to either 100 char</p><p>  // or eos starting at element 5</p><p>  "with" + s3.substr(5, 100) +</p><p>  // OK to copy a single char this way</p><p>  s1.substr(37, 1);</p><p>  cout &lt;&lt; quoteMe &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The <strong>string</strong> member function <strong>substr( )</strong> takes a starting position as its first argument and the number of characters to select as the second argument. Both arguments have default values. If you say <strong>substr( )</strong> with an empty argument list, you produce a copy of the entire <strong>string</strong>; so this is a convenient way to duplicate a <strong>string</strong><sup><strong>.</strong></sup></p><p>Here’s the output from the program:</p><p>What is</p><p>doing</p><p>Elvis in a UFO</p><p>What is that one clam doing with Elvis in a UFO?</p><empty-line/><p>Notice the final line of the example. C++ allows <strong>string</strong> initialization techniques to be mixed in a single statement, a flexible and convenient feature. Also notice that the last initializer copies <emphasis>just one character</emphasis> from the source <strong>string</strong><sup><strong>.</strong></sup></p><p>Another slightly more subtle initialization technique involves the use of the <strong>string</strong> iterators <strong>string::begin( )</strong> and <strong>string::end( ).</strong> This technique treats a <strong>string</strong> like a <emphasis>container</emphasis> object (which you’ve seen primarily in the form of <strong>vector</strong> so far—you’ll see many more containers in Chapter 7), which uses <emphasis>iterators</emphasis> to indicate the start and end of a sequence of characters. In this way you can hand a <strong>string</strong> constructor two iterators, and it copies from one to the other into the new <strong>string</strong>:<sup>.</sup></p><p>//: C03:StringIterators.cpp</p><p>#include &lt;string&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;cassert&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  string source("xxx");</p><p>  string s(source.begin(), source.end());</p><p>  assert(s == source);</p><p>} ///:~</p><empty-line/><p>The iterators are not restricted to <strong>begin( )</strong> and <strong>end( )</strong>; you can increment, decrement, and add integer offsets to them, allowing you to extract a subset of characters from the source <strong>string</strong><sup><strong>.</strong></sup></p><p>C++ strings may <emphasis>not</emphasis> be initialized with single characters or with ASCII or other integer values. You can initialize a string with a number of copies of a single character, however<sup>.</sup></p><p>//: C03:UhOh.cpp</p><p>#include &lt;string&gt;</p><p>#include &lt;cassert&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  // Error: no single char inits</p><p>  //! string nothingDoing1('a');</p><p>  // Error: no integer inits</p><p>  //! string nothingDoing2(0x37);</p><p>  // The following is legal:</p><p>  string okay(5, 'a');</p><p>  assert(okay == string("aaaaa"));</p><p>} ///:~</p><empty-line/></section><section><title><p>Operating on strings</p></title><section><p>If you’ve programmed in C, you are accustomed to the convenience of a large family of functions for writing, searching, modifying, and copying <strong>char</strong> arrays. However, there are two unfortunate aspects of the Standard C library functions for handling <strong>char</strong> arrays. First, there are two loosely organized families of them: the "plain" group, and the ones that require you to supply a count of the number of characters to be considered in the operation at hand. The roster of functions in the C <strong>char</strong> array handling library shocks the unsuspecting user with a long list of cryptic, mostly unpronounceable names. Although the kinds and number of arguments to the functions are somewhat consistent, to use them properly you must be attentive to details of function naming and parameter passing<sup>.</sup></p><p>The second inherent trap of the standard C <strong>char</strong> array tools is that they all rely explicitly on the assumption that the character array includes a null terminator. If by oversight or error the null is omitted or overwritten, there’s little to keep the C <strong>char</strong> array handling functions from manipulating the memory beyond the limits of the allocated space, sometimes with disastrous results<sup>.</sup></p><p>C++ provides a vast improvement in the convenience and safety of <strong>string</strong> objects. For purposes of actual string handling operations, there are about the same number of distinct member function names in the <strong>string</strong> class as there are functions in the C library, but because of overloading there is much more functionality. Coupled with sensible naming practices and the judicious use of default arguments, these features combine to make the <strong>string</strong> class much easier to use than the C library<sup>.</sup></p></section><section><title><p>Appending, inserting, and concatenating strings</p></title><p>One of the most valuable and convenient aspects of C++ strings is that they grow as needed, without intervention on the part of the programmer. Not only does this make string-handling code inherently more trustworthy, it also almost entirely eliminates a tedious "housekeeping" chore—keeping track of the bounds of the storage in which your strings live. For example, if you create a string object and initialize it with a string of 50 copies of ‘X’, and later store in it 50 copies of "Zowie", the object itself will reallocate sufficient storage to accommodate the growth of the data. Perhaps nowhere is this property more appreciated than when the strings manipulated in your code change size and you don’t know how big the change is. Appending, concatenating, and inserting strings often give rise to this circumstance, but the string member functions <strong>append( )</strong> and <strong>insert( )</strong> transparently reallocate storage when a string grows<sup>.</sup></p><p>//: C03:StrSize.cpp</p><p>#include &lt;string&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  string bigNews("I saw Elvis in a UFO. ");</p><p>  cout &lt;&lt; bigNews &lt;&lt; endl;</p><p>  // How much data have we actually got?</p><p>  cout &lt;&lt; "Size = " &lt;&lt; bigNews.size() &lt;&lt; endl;</p><p>  // How much can we store without reallocating</p><p>  cout &lt;&lt; "Capacity = "</p><p>    &lt;&lt; bigNews.capacity() &lt;&lt; endl;</p><p>  // Insert this string in bigNews immediately</p><p>  // before bigNews[1]</p><p>  bigNews.insert(1, " thought I");</p><p>  cout &lt;&lt; bigNews &lt;&lt; endl;</p><p>  cout &lt;&lt; "Size = " &lt;&lt; bigNews.size() &lt;&lt; endl;</p><p>  cout &lt;&lt; "Capacity = "</p><p>    &lt;&lt; bigNews.capacity() &lt;&lt; endl;</p><p>  // Make sure that there will be this much space</p><p>  bigNews.reserve(500);</p><p>  // Add this to the end of the string</p><p>  bigNews.append("I've been working too hard.");</p><p>  cout &lt;&lt; bigNews &lt;&lt; endl;</p><p>  cout &lt;&lt; "Size = " &lt;&lt; bigNews.size() &lt;&lt; endl;</p><p>  cout &lt;&lt; "Capacity = "</p><p>    &lt;&lt; bigNews.capacity() &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>Here is the output from one particular compiler:<sup>.</sup></p><p>I saw Elvis in a UFO.</p><p>Size = 22</p><p>Capacity = 31</p><p>I thought I saw Elvis in a UFO.</p><p>Size = 32</p><p>Capacity = 47</p><p>I thought I saw Elvis in a UFO. I've been</p><p>working too hard.</p><p>Size = 59</p><p>Capacity = 511</p><empty-line/><p>This example demonstrates that even though you can safely relinquish much of the responsibility for allocating and managing the memory your <strong>string</strong>s occupy, C++ <strong>string</strong>s provide you with several tools to monitor and manage their size. Notice the ease with which we changed the size of the storage allocated to the string. The <strong>size( ) </strong>function, of course, returns the number of characters currently stored in the string and is identical to the <strong>length( )</strong> member function. The <strong>capacity( ) </strong>function returns the size of the current underlying allocation, meaning the number of characters the string can hold without requesting more storage. The <strong>reserve( )</strong> function is an optimization mechanism that allows you to indicate your intention to specify a certain amount of storage for future use; <strong>capacity( )</strong> always returns a value at least as large as the most recent call to <strong>reserve( )</strong>. A <strong>resize( )</strong> function appends spaces if the new size is greater than the current string size or truncates the string otherwise. (An overload of <strong>resize( )</strong> allows you to specify a different character to append.)<sup>.</sup></p><p>The exact fashion in which the <strong>string</strong> member functions allocate space for your data depends on the implementation of the library. When we tested one implementation with the previous example, it appeared that reallocations occurred on even word (that is, full-integer) boundaries, with one byte held back. The architects of the <strong>string</strong> class have endeavored to make it possible to mix the use of C <strong>char</strong> arrays and C++ string objects, so it is likely that figures reported by <strong>StrSize.cpp</strong> for capacity reflect that, in this particular implementation, a byte is set aside to easily accommodate the insertion of a null terminator<sup>.</sup></p></section><section><title><p>Replacing string characters</p></title><p>The <strong>insert( ) </strong>function is particularly nice because it absolves you of making sure the insertion of characters in a string won’t overrun the storage space or overwrite the characters immediately following the insertion point. Space grows, and existing characters politely move over to accommodate the new elements. Sometimes, however, this might not be what you want to happen. If you want the size of the string to remain unchanged, use the <strong>replace( )</strong> function to overwrite characters. There are quite a number of overloaded versions of <strong>replace( )</strong>, but the simplest one takes three arguments: an integer indicating where to start in the string, an integer indicating how many characters to eliminate from the original string, and the replacement string (which can be a different number of characters than the eliminated quantity). Here’s a simple example:<sup>.</sup></p><p>//: C03:StringReplace.cpp</p><p>// Simple find-and-replace in strings</p><p>#include &lt;cassert&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  string s("A piece of text");</p><p>  string tag("$tag$");</p><p>  s.insert(8, tag + ' ');</p><p>  assert(s == "A piece $tag$ of text");</p><p>  int start = s.find(tag);</p><p>  assert(start == 8);</p><p>  assert(tag.size() == 5);</p><p>  s.replace(start, tag.size(), "hello there");</p><p>  assert(s == "A piece hello there of text");</p><p>} ///:~</p><empty-line/><p>The <strong>tag</strong> is first inserted into <strong>s</strong> (notice that the insert happens <emphasis>before</emphasis> the value indicating the insert point and that an extra space was added after <strong>tag</strong>), and then it is found and replaced<sup>.</sup></p><p>You should actually check to see if you’ve found anything before you perform a <strong>replace( )</strong>. The previous example replaces with a <strong>char*</strong>, but there’s an overloaded version that replaces with a <strong>string</strong>. Here’s a more complete demonstration <strong>replace( ):</strong></p><p>//: C03:Replace.cpp</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cstddef&gt;  // for size_t</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>void replaceChars(string&amp; modifyMe,</p><p>  const string&amp; findMe, const string&amp; newChars) {</p><p>  // Look in modifyMe for the "find string"</p><p>  // starting at position 0</p><p>  size_t i = modifyMe.find(findMe, 0);</p><p>  // Did we find the string to replace?</p><p>  if (i != string::npos)</p><p>    // Replace the find string with newChars</p><p>    modifyMe.replace(i, findMe.size(), newChars);</p><p>}</p><empty-line/><p>int main() {</p><p>  string bigNews =</p><p>   "I thought I saw Elvis in a UFO. "</p><p>   "I have been working too hard.";</p><p>  string replacement("wig");</p><p>  string findMe("UFO");</p><p>  // Find "UFO" in bigNews and overwrite it:</p><p>  replaceChars(bigNews, findMe, replacement);</p><p>  assert(bigNews == "I thought I saw Elvis in a "</p><p>         "wig. I have been working too hard.");</p><p>} ///:~</p><empty-line/><p>If <strong>replace</strong> doesn’t find the search string, it returns <strong>string::npos</strong>. The <strong>npos</strong> data member is a static constant member of the <strong>string</strong> class that represents a nonexistent character position.<a l:href="#n30" type="note">[30]</a></p><p>Unlike <strong>insert( )</strong>, <strong>replace( )</strong> won’t grow the <strong>string</strong>’s storage space if you copy new characters into the middle of an existing series of array elements. However, it <emphasis>will</emphasis> grow the storage space if needed, for example, when you make a "replacement" that would expand the original string beyond the end of the current allocation. Here’s an example:<sup>.</sup></p><p>//: C03:ReplaceAndGrow.cpp</p><p>#include &lt;cassert&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  string bigNews("I have been working the grave.");</p><p>  string replacement("yard shift.");</p><p>  // The first arg says "replace chars</p><p>  // beyond the end of the existing string":</p><p>  bigNews.replace(bigNews.size() - 1,</p><p>    replacement.size(), replacement);</p><p>  assert(bigNews == "I have been working the "</p><p>         "graveyard shift.");</p><p>} ///:~</p><empty-line/><p>The call to <strong>replace( ) </strong>begins "replacing" beyond the end of the existing array, which is equivalent to an append operation. Notice that in this example <strong>replace( )</strong> expands the array accordingly<sup>.</sup></p><p>You may have been hunting through this chapter trying to do something relatively simple such as replace all the instances of one character with a different character. Upon finding the previous material on replacing, you thought you found the answer, but then you started seeing groups of characters and counts and other things that looked a bit too complex. Doesn’t <strong>string</strong> have a way to just replace one character with another everywhere?<sup>.</sup></p><p>You can easily write such a function using the <strong>find( )</strong> and <strong>replace( )</strong> member functions as follows:</p><p>//: C03:ReplaceAll.cpp {O}</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>string&amp; replaceAll(string&amp; context, const string&amp; from,</p><p>  const string&amp; to) {</p><p>  size_t lookHere = 0;</p><p>  size_t foundHere;</p><p>while ((foundHere = context.find(from, lookHere))</p><p>  != string::npos) {</p><p>    context.replace(foundHere, from.size(), to);</p><p>lookHere = foundHere + to.size();</p><p>  }</p><p>  return context;</p><p>} ///:~</p><empty-line/><p>The version of <strong>find( )</strong> used here takes as a second argument the position to start looking in and returns <strong>string::npos</strong> if it doesn’t find it. It is important to advance the position held in the variable <strong>lookHere</strong> past the replacement string, of course, in case <strong>from</strong> is a substring of <strong>to</strong>. The following program tests the <strong>replaceAll</strong> function:<sup>.</sup></p><p>//: C03:ReplaceAllTest.cpp</p><p>//{-msc}</p><p>//{L} ReplaceAll</p><p>#include &lt;iostream&gt;</p><p>#include &lt;cassert&gt;</p><p>using namespace std;</p><empty-line/><p>string&amp; replaceAll(string&amp; context, const string&amp; from,</p><p>  const string&amp; to);</p><empty-line/><p>int main() {</p><p>  string text = "a man, a plan, a canal, panama";</p><p>  replaceAll(text, "an", "XXX");</p><p>  assert(text == "a mXXX, a plXXX, a cXXXal, pXXXama");</p><p>} ///:~</p><empty-line/><p>As you can see, the <strong>string</strong> class by itself doesn’t solve all possible problems. Many solutions have been left to the algorithms in the Standard library,<a l:href="#n31" type="note">[31]</a> because the <strong>string</strong> class can look just like an STL sequence (by virtue of the iterators discussed earlier). All the generic algorithms work on a "range" of elements within a container. Usually that range is just "from the beginning of the container to the end." A <strong>string</strong> object looks like a container of characters: to get the beginning of the range you use <strong>string::begin( ),</strong> and to get the end of the range you use <strong>string::end( )</strong>. The following example shows the use of the <strong>replace( )</strong> algorithm to replace all the instances of the single character ‘X’ with ‘Y’:<sup>.</sup></p><p>//: C03:StringCharReplace.cpp</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cassert&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  string s("aaaXaaaXXaaXXXaXXXXaaa");</p><p>  replace(s.begin(), s.end(), 'X', 'Y');</p><p>  assert(s == "aaaYaaaYYaaYYYaYYYYaaa");</p><p>} ///:~</p><empty-line/><p>Notice that this <strong>replace( )</strong> is <emphasis>not</emphasis> called as a member function of <strong>string</strong>. Also, unlike the <strong>string::replace( )</strong> functions that only perform one replacement, the <strong>replace( )</strong> algorithm replaces <emphasis>all instances</emphasis> of one character with another<sup>.</sup></p><p>The <strong>replace( )</strong> algorithm only works with single objects (in this case, <strong>char</strong> objects) and will not replace quoted <strong>char</strong> arrays or <strong>string</strong> objects. Since a <strong>string</strong> behaves like an STL sequence, a number of other algorithms can be applied to it, which might solve other problems that are not directly addressed by the <strong>string</strong> member functions<sup>.</sup></p></section><section><title><p>Concatenation using nonmember overloaded operators</p></title><p>One of the most delightful discoveries awaiting a C programmer learning about C++ <strong>string</strong> handling is how simply <strong>string</strong>s can be combined and appended using <strong>operator+</strong> and <strong>operator+=</strong>. These operators make combining <strong>string</strong>s syntactically similar to adding numeric data<sup>.</sup></p><p>//: C03:AddStrings.cpp</p><p>#include &lt;string&gt;</p><p>#include &lt;cassert&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  string s1("This ");</p><p>  string s2("That ");</p><p>  string s3("The other ");</p><p>  // operator+ concatenates strings</p><p>  s1 = s1 + s2;</p><p>  assert(s1 == "This That ");</p><p>  // Another way to concatenates strings</p><p>  s1 += s3;</p><p>  assert(s1 == "This That The other ");</p><p>  // You can index the string on the right</p><p>  s1 += s3 + s3[4] + "ooh lala";</p><p>  assert(s1 == "This That The other The other "</p><p>        "oooh lala");</p><p>} ///:~</p><empty-line/><empty-line/><p>Using the <strong>operator+</strong> and <strong>operator+= </strong>operators is a flexible and convenient way to combine <strong>string</strong> data. On the right side of the statement, you can use almost any type that evaluates to a group of one or more characters<sup>.</sup></p></section></section><section><title><p>Searching in strings</p></title><section><p>The <strong>find</strong> family of <strong>string</strong> member functions allows you to locate a character or group of characters within a given string. Here are the members of the <strong>find</strong> family and their general usage :</p><table><tr align="left"><td align="left" valign="top">string find member function</td><td align="left" valign="top">What/how it finds </td></tr><tr align="left"><td align="left" valign="top"><strong>find( )</strong></td><td align="left" valign="top">Searches a string for a specified character or group of characters and returns the starting position of the first occurrence found or npos if no match is found. (<strong>npos</strong> is a <strong>const</strong> of –1 [cast as a <strong>std::size_t</strong>] and indicates that a search failed.) </td></tr><tr align="left"><td align="left" valign="top"><strong>find_first_of( )</strong></td><td align="left" valign="top">Searches a target string and returns the position of the first match of <emphasis>any</emphasis> character in a specified group. If no match is found, it returns npos.</td></tr><tr align="left"><td align="left" valign="top"><strong>find_last_of( )</strong></td><td align="left" valign="top">Searches a target string and returns the position of the last match of <emphasis>any</emphasis> character in a specified group. If no match is found, it returns npos.</td></tr><tr align="left"><td align="left" valign="top"><strong>find_first_not_of( )</strong></td><td align="left" valign="top">Searches a target string and returns the position of the first element that <emphasis>doesn’t</emphasis> match <emphasis>any</emphasis> character in a specified group. If no such element is found, it returns npos.</td></tr><tr align="left"><td align="left" valign="top"><strong>find_last_not_of( )</strong></td><td align="left" valign="top">Searches a target string and returns the position of the element with the largest subscript that <emphasis>doesn’t</emphasis> match <emphasis>any</emphasis> character in a specified group. If no such element is found, it returns npos.</td></tr><tr align="left"><td align="left" valign="top"><strong>rfind( )</strong></td><td align="left" valign="top">Searches a string from end to beginning for a specified character or group of characters and returns the starting position of the match if one is found. If no match is found, it returns <strong>npos</strong>.</td></tr></table><empty-line/><p>The simplest use of <strong>find( ) </strong>searches for one or more characters in a <strong>string</strong>. This overloaded version of <strong>find( ) </strong>takes a parameter that specifies the character(s) for which to search and optionally a parameter that tells it where in the string to begin searching for the occurrence of a substring. (The default position at which to begin searching is 0.) By setting the call to <strong>find </strong>inside a loop, you can easily move through a string, repeating a search to find all the occurrences of a given character or group of characters within the string<sup>.</sup></p><p>The following program uses the method of <emphasis>The Sieve of Eratosthenes</emphasis> to find prime numbers less than 50. This method starts with the number 2, marks all subsequent multiples of 2 as not prime, and repeats the process for the next prime candidate. Notice that we define the string object <strong>sieveChars</strong> using a constructor idiom that sets the initial size of the character array and writes the value ‘P’ to each of its member<sup>.</sup></p><p>//: C03:Sieve.cpp</p><p>//{L} ../TestSuite/Test</p><p>#include &lt;cmath&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;string&gt;</p><p>#include "../TestSuite/Test.h"</p><p>using namespace std;</p><empty-line/><p>class SieveTest : public TestSuite::Test {</p><p>  string sieveChars;</p><p>public:</p><p>  // Create a 50 char string and set each</p><p>  // element to 'P' for Prime</p><p>SieveTest() : sieveChars(50, 'P') {}</p><p>  void run() {</p><p>    findPrimes();</p><p>    testPrimes();</p><p>  }</p><p>  bool isPrime(int p) {</p><p>    if (p == 0 || p == 1) return false;</p><p>    int root = int(sqrt(double(p)));</p><p>    for (int i = 2; i &lt;= root; ++i)</p><p>      if (p % i == 0) return false;</p><p>    return true;</p><p>  }</p><p>  void findPrimes() {</p><p>    // By definition neither 0 nor 1 is prime.</p><p>    // Change these elements to "N" for Not Prime</p><p>    sieveChars.replace(0, 2, "NN");</p><p>    // Walk through the array:</p><p>    size_t sieveSize = sieveChars.size();</p><p>    int root = int(sqrt(double(sieveSize)));</p><p>    for (int i = 2; i &lt;= root; ++i)</p><p>      // Find all the multiples:</p><p>      for (size_t factor = 2; factor * i &lt; sieveSize;</p><p>           ++factor)</p><p>        sieveChars[factor * i] = 'N';</p><p>  }</p><p>  void testPrimes() {</p><p>    size_t i = sieveChars.find('P');</p><p>    while (i != string::npos) {</p><p>      test_(isPrime(i++));</p><p>      i = sieveChars.find('P', i);</p><p>    }</p><p>    i = sieveChars.find_first_not_of('P');</p><p>    while (i != string::npos) {</p><p>      test_(!isPrime(i++));</p><p>      i = sieveChars.find_first_not_of('P', i);</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  SieveTest t;</p><p>  t.run();</p><p>  return t.report();</p><p>} ///:~</p><empty-line/><p>The <strong>find( )</strong> function allows you to walk forward through a <strong>string</strong>, detecting multiple occurrences of a character or a group of characters, and <strong>find_first_not_of( )</strong> allows you to find other characters or substrings<sup>.</sup></p><p>There are no functions in the <strong>string </strong>class to change the case of a string, but you can easily create these functions using the Standard C library functions <strong>toupper( )</strong> and <strong>tolower( )</strong>, which change the case of one character at a time. The following example illustrates a case-insensitive search:<sup>.</sup></p><p>//: C03:Find.cpp</p><p>//{L} ../TestSuite/Test</p><p>#include &lt;cctype&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;string&gt;</p><p>#include "../TestSuite/Test.h"</p><p>using namespace std;</p><empty-line/><p>// Make an uppercase copy of s</p><p>string upperCase(const string&amp; s) {</p><p>  string upper(s);</p><p>  for(size_t i = 0; i &lt; s.length(); ++i)</p><p>    upper[i] = toupper(upper[i]);</p><p>  return upper;</p><p>}</p><empty-line/><p>// Make a lowercase copy of s</p><p>string lowerCase(const string&amp; s) {</p><p>  string lower(s);</p><p>  for(size_t i = 0; i &lt; s.length(); ++i)</p><p>    lower[i] = tolower(lower[i]);</p><p>  return lower;</p><p>}</p><empty-line/><p>class FindTest : public TestSuite::Test {</p><p>  string chooseOne;</p><p>public:</p><p>  FindTest() : chooseOne("Eenie, Meenie, Miney, Mo") {}</p><p>  void testUpper() {</p><p>    string upper = upperCase(chooseOne);</p><p>    const string LOWER = "abcdefghijklmnopqrstuvwxyz";</p><p>    test_(upper.find_first_of(LOWER) == string::npos);</p><p>  }</p><p>  void testLower() {</p><p>    string lower = lowerCase(chooseOne);</p><p>    const string UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";</p><p>    test_(lower.find_first_of(UPPER) == string::npos);</p><p>  }</p><p>  void testSearch() {</p><p>    // Case sensitive search</p><p>    size_t i = chooseOne.find("een");</p><p>    test_(i == 8);</p><p>    // Search lowercase:</p><p>    string test = lowerCase(chooseOne);</p><p>    i = test.find("een");</p><p>    test_(i == 0);</p><p>    i = test.find("een", ++i);</p><p>    test_(i == 8);</p><p>    i = test.find("een", ++i);</p><p>    test_(i == string::npos);</p><p>    // Search uppercase:</p><p>    test = upperCase(chooseOne);</p><p>    i = test.find("EEN");</p><p>    test_(i == 0);</p><p>    i = test.find("EEN", ++i);</p><p>    test_(i == 8);</p><p>    i = test.find("EEN", ++i);</p><p>    test_(i == string::npos);</p><p>  }</p><p>  void run() {</p><p>    testUpper();</p><p>    testLower();</p><p>    testSearch();</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  FindTest t;</p><p>  t.run();</p><p>  return t.report();</p><p>} ///:~</p><empty-line/><p>Both the <strong>upperCase( )</strong> and <strong>lowerCase( )</strong> functions follow the same form: they make a copy of the argument <strong>string</strong> and change the case. The <strong>NewFind.cpp</strong> program isn’t the best solution to the case-sensitivity problem, so we’ll revisit it when we examine <strong>string</strong> comparisons<sup>.</sup></p></section><section><title><p>Finding in reverse</p></title><p>Sometimes it’s necessary to search through a <strong>string</strong> from end to beginning, if you need to find the data in "last in / first out" order. The string member function <strong>rfind( )</strong> handles this job<sup>.</sup></p><p>//: C03:Rparse.cpp</p><p>//{L} ../TestSuite/Test</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../TestSuite/Test.h"</p><p>using namespace std;</p><empty-line/><p>class RparseTest : public TestSuite::Test {</p><p>  // To store the words:</p><p>  vector&lt;string&gt; strings;</p><p>public:</p><p>  void parseForData() {</p><p>    // The ';' characters will be delimiters</p><p>    string s("now.;sense;make;to;going;is;This");</p><p>    // The last element of the string:</p><p>    int last = s.size();</p><p>    // The beginning of the current word:</p><p>    int current = s.rfind(';');</p><p>    // Walk backward through the string:</p><p>    while(current != string::npos){</p><p>      // Push each word into the vector.</p><p>      // Current is incremented before copying to</p><p>      // avoid copying the delimiter:</p><p>      ++current;</p><p>      strings.push_back(</p><p>        s.substr(current, last - current));</p><p>      // Back over the delimiter we just found,</p><p>      // and set last to the end of the next word:</p><p>      current -= 2;</p><p>      last = current + 1;</p><p>      // Find the next delimiter</p><p>      current = s.rfind(';', current);</p><p>    }</p><p>    // Pick up the first word - it's not</p><p>    // preceded by a delimiter</p><p>    strings.push_back(s.substr(0, last));</p><p>  }</p><p>  void testData() {</p><p>    // Test order them in the new order:</p><p>    test_(strings[0] == "This");</p><p>    test_(strings[1] == "is");</p><p>    test_(strings[2] == "going");</p><p>    test_(strings[3] == "to");</p><p>    test_(strings[4] == "make");</p><p>    test_(strings[5] == "sense");</p><p>    test_(strings[6] == "now.");</p><p>    string sentence;</p><p>    for(int i = 0; i &lt; strings.size() - 1; i++)</p><p>      sentence += strings[i] += " ";</p><p>    // Manually put last word in to avoid an extra space</p><p>    sentence += strings[strings.size() - 1];</p><p>    test_(sentence == "This is going to make sense now.");</p><p>  }</p><p>  void run() {</p><p>    parseForData();</p><p>    testData();</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  RparseTest t;</p><p>  t.run();</p><p>  return t.report();</p><p>} ///:~</p><empty-line/><p>The string member function <strong>rfind( )</strong> backs through the string looking for tokens and reporting the array index of matching characters or <strong>string::npos</strong> if it is unsuccessful<sup>.</sup></p></section><section><title><p>Finding first/last of a set of characters</p></title><p>The <strong>find_first_of( )</strong> and <strong>find_last_of( )</strong> member functions can be conveniently put to work to create a little utility that will strip whitespace characters from both ends of a string. Notice that it doesn’t touch the original string, but instead returns a new string:<sup>.</sup></p><p>//: C03:Trim.h</p><p>#ifndef TRIM_H</p><p>#define TRIM_H</p><p>#include &lt;string&gt;</p><p>// General tool to strip spaces from both ends:</p><p>inline std::string trim(const std::string&amp; s) {</p><p>  if(s.length() == 0)</p><p>    return s;</p><p>  int beg = s.find_first_not_of(" \a\b\f\n\r\t\v");</p><p>  int end = s.find_last_not_of(" \a\b\f\n\r\t\v");</p><p>  if(beg == std::string::npos) // No non-spaces</p><p>    return "";</p><p>  return std::string(s, beg, end - beg + 1);</p><p>}</p><p>#endif // TRIM_H ///:~</p><empty-line/><p>The first test checks for an empty <strong>string</strong>; in that case, no tests are made, and a copy is returned. Notice that once the end points are found, the <strong>string</strong> constructor builds a new <strong>string</strong> from the old one, giving the starting count and the length<sup>.</sup></p><p>Testing such a general-purpose tool needs to be thorough:<sup>.</sup></p><p>//: C03:TrimTest.cpp</p><p>//{L} ../TestSuite/Test</p><p>#include &lt;iostream&gt;</p><p>#include "Trim.h"</p><p>#include "../TestSuite/Test.h"</p><p>using namespace std;</p><empty-line/><p>string s[] = {</p><p>  " \t abcdefghijklmnop \t ",</p><p>  "abcdefghijklmnop \t ",</p><p>  " \t abcdefghijklmnop",</p><p>  "a", "ab", "abc", "a b c",</p><p>  " \t a b c \t ", " \t a \t b \t c \t ",</p><p>  "\t \n \r \v \f",</p><p>  "" // Must also test the empty string</p><p>};</p><empty-line/><p>class TrimTest : public TestSuite::Test {</p><p>public:</p><p>  void testTrim() {</p><p>    test_(trim(s[0]) == "abcdefghijklmnop");</p><p>    test_(trim(s[1]) == "abcdefghijklmnop");</p><p>    test_(trim(s[2]) == "abcdefghijklmnop");</p><p>    test_(trim(s[3]) == "a");</p><p>    test_(trim(s[4]) == "ab");</p><p>    test_(trim(s[5]) == "abc");</p><p>    test_(trim(s[6]) == "a b c");</p><p>    test_(trim(s[7]) == "a b c");</p><p>    test_(trim(s[8]) == "a \t b \t c");</p><p>    test_(trim(s[9]) == "");</p><p>    test_(trim(s[10]) == "");</p><p>  }</p><p>  void run() {</p><p>    testTrim();</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  TrimTest t;</p><p>  t.run();</p><p>  return t.report();</p><p>} ///:~</p><empty-line/><p>In the array of <strong>strings</strong>, you can see that the character arrays are automatically converted to <strong>string</strong> objects. This array provides cases to check the removal of spaces and tabs from both ends, as well as ensuring that spaces and tabs are not removed from the middle of a <strong>string</strong><sup><strong>.</strong></sup></p></section><section><title><p>Removing characters from strings</p></title><p>Removing characters is easy and efficient with the <strong>erase( )</strong> member function, which takes two arguments: where to start removing characters (which defaults to <strong>0</strong>), and how many to remove (which defaults to <strong>string::npos).</strong> If you specify more characters than remain in the string, the remaining characters are all erased anyway (so calling <strong>erase( )</strong> without any arguments removes all characters from a string). Sometimes it’s useful to take an HTML file and strip its tags and special characters so that you have something approximating the text that would be displayed in the Web browser, only as a plain text file. The following uses <strong>erase( )</strong> to do the job:<sup>.</sup></p><p>//: C03:HTMLStripper.cpp</p><p>//{L} ReplaceAll</p><p>// Filter to remove html tags and markers</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cmath&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>string&amp; replaceAll(string&amp; context, const string&amp; from,</p><p>  const string&amp; to);</p><empty-line/><p>string&amp; stripHTMLTags(string&amp; s) {</p><p>  static bool inTag = false;</p><p>  bool done = false;</p><p>  while (!done) {</p><p>    if (inTag) {</p><p>      // The previous line started an HTML tag</p><p>      // but didn't finish. Must search for '&gt;'.</p><p>      size_t rightPos = s.find('&gt;');</p><p>      if (rightPos != string::npos) {</p><p>        inTag = false;</p><p>        s.erase(0, rightPos + 1);</p><p>      }</p><p>      else {</p><p>        done = true;</p><p>        s.erase();</p><p>      }</p><p>    }</p><p>    else {</p><p>      // Look for start of tag:</p><p>      size_t leftPos = s.find('&lt;');</p><p>      if (leftPos != string::npos) {</p><p>        // See if tag close is in this line</p><p>        size_t rightPos = s.find('&gt;');</p><p>        if (rightPos == string::npos) {</p><p>          inTag = done = true;</p><p>          s.erase(leftPos);</p><p>        }</p><p>        else</p><p>          s.erase(leftPos, rightPos - leftPos + 1);</p><p>      }</p><p>      else</p><p>        done = true;</p><p>    }</p><p>  }</p><p>  // Remove all special HTML characters</p><p>  replaceAll(s, "&lt;", "&lt;");</p><p>  replaceAll(s, "&gt;", "&gt;");</p><p>  replaceAll(s, "&amp;&amp;", "&amp;");</p><p>  replaceAll(s, "&amp;nbsp;", " ");</p><p>  // Etc...</p><p>  return s;</p><p>}</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  requireArgs(argc, 1,</p><p>    "usage: HTMLStripper InputFile");</p><p>  ifstream in(argv[1]);</p><p>  assure(in, argv[1]);</p><p>  string s;</p><p>  while(getline(in, s))</p><p>    if (!stripHTMLTags(s).empty())</p><p>      cout &lt;&lt; s &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>This example will even strip HTML tags that span multiple lines.<a l:href="#n32" type="note">[32]</a> This is accomplished with the static flag, <strong>inTag</strong>, which is <strong>true</strong> whenever the start of a tag is found, but the accompanying tag end is not found in the same line. All forms of <strong>erase( )</strong> appear in the <strong>stripHTMLFlags( )</strong> function.<a l:href="#n33" type="note">[33]</a> The version of <strong>getline( )</strong> we use here is a global function declared in the <strong>&lt;string&gt;</strong> header and is handy because it stores an arbitrarily long line in its <strong>string</strong> argument. You don’t have to worry about the dimension of a character array as you do with <strong>istream::getline( )</strong>. Notice that this program uses the <strong>replaceAll( )</strong> function from earlier in this chapter. In the next chapter, we’ll use string streams to create a more elegant solution<sup>.</sup></p></section><section><title><p>Comparing strings</p></title><p>Comparing strings is inherently different from comparing numbers. Numbers have constant, universally meaningful values. To evaluate the relationship between the magnitudes of two strings, you must make a <emphasis>lexical comparison</emphasis>. Lexical comparison means that when you test a character to see if it is "greater than" or "less than" another character, you are actually comparing the numeric representation of those characters as specified in the collating sequence of the character set being used. Most often this will be the ASCII collating sequence, which assigns the printable characters for the English language numbers in the range 32 through 127 decimal. In the ASCII collating sequence, the first "character" in the list is the space, followed by several common punctuation marks, and then uppercase and lowercase letters. With respect to the alphabet, this means that the letters nearer the front have lower ASCII values than those nearer the end. With these details in mind, it becomes easier to remember that when a lexical comparison that reports <strong>s1</strong> is "greater than" <strong>s2</strong>, it simply means that when the two were compared, the first differing character in <strong>s1</strong> came later in the alphabet than the character in that same position in <strong>s2</strong><sup><strong>.</strong></sup></p><p>C++ provides several ways to compare strings, and each has advantages. The simplest to use are the nonmember, overloaded operator functions: <strong>operator ==, operator != operator &gt;, operator &lt;, operator &gt;=, </strong>and <strong>operator &lt;=</strong><sup>.</sup></p><p>//: C03:CompStr.cpp</p><p>//{L} ../TestSuite/Test</p><p>#include &lt;string&gt;</p><p>#include "../TestSuite/Test.h"</p><p>using namespace std;</p><empty-line/><p>class CompStrTest : public TestSuite::Test {</p><p>public:</p><p>  void run() {</p><p>    // Strings to compare</p><p>    string s1("This");</p><p>    string s2("That");</p><p>    test_(s1 == s1);</p><p>    test_(s1 != s2);</p><p>    test_(s1 &gt; s2);</p><p>    test_(s1 &gt;= s2);</p><p>    test_(s1 &gt;= s1);</p><p>    test_(s2 &lt; s1);</p><p>    test_(s2 &lt;= s1);</p><p>    test_(s1 &lt;= s1);</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  CompStrTest t;</p><p>  t.run();</p><p>  return t.report();</p><p>} ///:~</p><empty-line/><p>The overloaded comparison operators are useful for comparing both full strings and individual string character elements<sup>.</sup></p><p>Notice in the following code fragment the flexibility of argument types on both the left and right side of the comparison operators. For efficiency, the <strong>string</strong> class provides overloaded operators for the direct comparison of string objects, quoted literals, and pointers to C-style strings without having to create temporary <strong>string</strong> objects<sup>.</sup></p><p>// The lvalue is a quoted literal and</p><p>// the rvalue is a string</p><p>if("That" == s2)</p><p>  cout &lt;&lt; "A match" &lt;&lt; endl;</p><p>// The left operand below is a string and the right is a</p><p>// pointer to a C-style null terminated string</p><p>if(s1 != s2.c_str())</p><p>  cout &lt;&lt; "No match" &lt;&lt; endl;</p><empty-line/><p>The <strong>c_str( )</strong> function returns a <strong>const char*</strong> that points to a C-style, null-terminated string equivalent to the contents of the <strong>string</strong> object. This comes in handy when you want to pass a string to a standard C function, such as <strong>atoi( )</strong> or any of the functions defined in the <strong>&lt;cstring&gt;</strong> header. It is an error to use the value returned by <strong>c_str( )</strong> as non-<strong>const</strong> argument to any function<sup>.</sup></p><p>You won’t find the logical not (<strong>!</strong>) or the logical comparison operators (<strong>&amp;&amp;</strong> and <strong>||</strong>) among operators for a string. (Neither will you find overloaded versions of the bitwise C operators <strong>&amp;</strong>, <strong>|</strong>, <strong>^</strong>, or <strong>~</strong>.) The overloaded nonmember comparison operators for the string class are limited to the subset that has clear, unambiguous application to single characters or groups of characters<sup>.</sup></p><p>The <strong>compare( )</strong> member function offers you a great deal more sophisticated and precise comparison than the nonmember operator set. It provides overloaded versions that allow you to compare two complete strings, part of either string to a complete string, and subsets of two strings. The following example compares complete strings:<sup>.</sup></p><p>//: C03:Compare.cpp</p><p>// Demonstrates compare(), swap()</p><p>#include &lt;cassert&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  string first("This");</p><p>  string second("That");</p><p>  assert(first.compare(first) == 0);</p><p>  assert(second.compare(second) == 0);</p><p>  // Which is lexically greater?</p><p>  assert(first.compare(second) &gt; 0);</p><p>  assert(second.compare(first) &lt; 0);</p><p>  first.swap(second);</p><p>  assert(first.compare(second) &lt; 0);</p><p>  assert(second.compare(first) &gt; 0);</p><p>} ///:~</p><empty-line/><p>The <strong>swap( )</strong> function in this example does what its name implies: it exchanges the contents of its object and argument. To compare a subset of the characters in one or both strings, you add arguments that define where to start the comparison and how many characters to consider. For example, we can use the overloaded version of <strong>compare( )</strong>:<sup>.</sup></p><p><strong>s1.compare(s1StartPos, s1NumberChars, s2, s2StartPos, s2NumberChars);</strong><sup>.</sup></p><p>Here’s an example:<sup>.</sup></p><p>//: C03:Compare2.cpp</p><p>// Illustrate overloaded compare()</p><p>#include &lt;cassert&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  string first("This is a day that will live in infamy");</p><p>  string second("I don't believe that this is what "</p><p> "I signed up for");</p><p>  // Compare "his is" in both strings:</p><p>  assert(first.compare(1, 7, second, 22, 7) == 0);</p><p>  // Compare "his is a" to "his is w":</p><p>  assert(first.compare(1, 9, second, 22, 9) &lt; 0);</p><p>} ///:~</p><empty-line/><p>In the examples so far, we have used C-style array indexing syntax to refer to an individual character in a string. C++ strings provide an alternative to the <strong>s[n] </strong>notation: the <strong>at( )</strong> member. These two indexing mechanisms produce the same result in C++ if all goes well:<sup>.</sup></p><p>//: C03:StringIndexing.cpp</p><p>#include &lt;cassert&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><p>int main(){</p><p>  string s("1234");</p><p>  assert(s[1] == '2');</p><p>  assert(s.at(1) == '2');</p><p>} ///:~</p><empty-line/><p>There is one important difference, however, between <strong>[ ]</strong> and <strong>at( )</strong>. When you try to reference an array element that is out of bounds, <strong>at( ) </strong>will do you the kindness of throwing an exception, while ordinary <strong>[ ] </strong>subscripting syntax will leave you to your own devices:<sup>.</sup></p><p>//: C03:BadStringIndexing.cpp</p><p>#include &lt;exception&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main(){</p><p>  string s("1234");</p><p>  // at() saves you by throwing an exception:</p><p>  try {</p><p>    s.at(5);</p><p>  } catch(exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>Responsible programmers will not use errant indexes, but should you want to benefits of automatic index checking, using <strong>at( ) </strong>in place of <strong>[ ] </strong>will give you a chance to gracefully recover from references to array elements that don’t exist. Execution of this program on one of our test compilers gave the following output:</p><p>invalid string position</p><empty-line/><p>The <strong>at( )</strong> member throws an object of class <strong>out_of_range</strong>, which derives (ultimately) from <strong>std::exception. </strong>By catching this object in an exception handler, you can take appropriate remedial actions such as recalculating the offending subscript or growing the array. Using <strong>string::operator[]( )</strong> gives no such protection and is as dangerous as <strong>char</strong> array processing in C.<a l:href="#n34" type="note">[34]</a></p></section><section><title><p>Strings and character traits</p></title><p>The program <strong>Find.cpp</strong> earlier in this chapter leads us to ask the obvious question: Why isn’t case-insensitive comparison part of the standard <strong>string</strong> class? The answer provides interesting background on the true nature of C++ string objects<sup>.</sup></p><p>Consider what it means for a character to have "case." Written Hebrew, Farsi, and Kanji don’t use the concept of upper- and lowercase, so for those languages this idea has no meaning. It would seem that if there were a way to designate some languages as "all uppercase" or "all lowercase," we could design a generalized solution. However, some languages that employ the concept of "case" <emphasis>also</emphasis> change the meaning of particular characters with diacritical marks: for example, the cedilla in Spanish, the circumflex in French, and the umlaut in German. For this reason, any case-sensitive collating scheme that attempts to be comprehensive will be nightmarishly complex to use<sup>.</sup></p><p>Although we usually treat the C++ <strong>string</strong> as a class, this is really not the case. The <strong>string</strong> type is actually a specialization of a more general constituent, the <strong>basic_string&lt; &gt;</strong> template. Observe how <strong>string</strong> is declared in the standard C++ header file:<a l:href="#n35" type="note">[35]</a></p><p>typedef basic_string&lt;char&gt; string;</p><empty-line/><p>To really understand the nature of the string class, it’s helpful to delve a bit deeper and look at the template on which it is based. Here’s the declaration of the <strong>basic_string&lt; &gt;</strong> template:<sup>.</sup></p><p>template&lt;class charT,</p><p>  class traits = char_traits&lt;charT&gt;,</p><p>  class allocator = allocator&lt;charT&gt; &gt;</p><p>  class basic_string;</p><empty-line/><p>In Chapter 5, we examine templates in great detail (much more than in Chapter 16 of Volume 1). For now, the main thing to notice about the two previous declarations is that the <strong>string</strong> type is created when the <strong>basic_string</strong> template is instantiated with <strong>char. </strong>Inside the <strong>basic_string&lt; &gt; </strong>template declaration, the line<sup>.</sup></p><p>class traits = char_traits&lt;charT&gt;,</p><empty-line/><p>tells us that the behavior of the class made from the <strong>basic_string&lt; &gt; </strong>template is specified by a class based on the template <strong>char_traits&lt; &gt;</strong>. Thus, the <strong>basic_string&lt; &gt;</strong> template provides for cases in which you need string-oriented classes that manipulate types other than <strong>char</strong> (wide characters, for example). To do this, the <strong>char_traits&lt; &gt; </strong>template controls the content and collating behaviors of a variety of character sets using the character comparison functions <strong>eq( )</strong> (equal), <strong>ne( )</strong> (not equal), and <strong>lt( )</strong> (less than) upon which the <strong>basic_string&lt; &gt; </strong>string comparison functions rely<sup>.</sup></p><p>This is why the string class doesn’t include case-insensitive member functions: that’s not in its job description. To change the way the string class treats character comparison, you must supply a different <strong>char_traits&lt; &gt;</strong> template, because that defines the behavior of the individual character comparison member functions<sup>.</sup></p><p>You can use this information to make a new type of <strong>string </strong>class that ignores case. First, we’ll define a new case-insensitive <strong>char_traits&lt; &gt;</strong> template that inherits from the existing template. Next, we’ll override only the members we need to change to make character-by-character comparison case insensitive. (In addition to the three lexical character comparison members mentioned earlier, we’ll also have to supply a new implementation for the <strong>char_traits</strong> functions <strong>find( )</strong> and <strong>compare( )</strong>.) Finally, we’ll <strong>typedef</strong> a new class based on <strong>basic_string</strong>, but using the case-insensitive <strong>ichar_traits</strong> template for its second argument<sup>.</sup></p><p>//: C03:ichar_traits.h</p><p>// Creating your own character traits</p><p>#ifndef ICHAR_TRAITS_H</p><p>#define ICHAR_TRAITS_H</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cctype&gt;</p><p>#include &lt;cmath&gt;</p><p>#include &lt;ostream&gt;</p><p>#include &lt;string&gt;</p><empty-line/><p>using std::toupper;</p><p>using std::tolower;</p><p>using std::ostream;</p><p>using std::string;</p><p>using std::char_traits;</p><p>using std::allocator;</p><p>using std::basic_string;</p><empty-line/><p>struct ichar_traits : char_traits&lt;char&gt; {</p><p>  // We'll only change character-by-</p><p>  // character comparison functions</p><p>  static bool eq(char c1st, char c2nd) {</p><p>    return toupper(c1st) == toupper(c2nd);</p><p>  }</p><p>  static bool ne(char c1st, char c2nd) {</p><p>    return !eq(c1st, c2nd);</p><p>  }</p><p>  static bool lt(char c1st, char c2nd) {</p><p>    return toupper(c1st) &lt; toupper(c2nd);</p><p>  }</p><p>  static int compare(const char* str1,</p><p>    const char* str2, size_t n) {</p><p>    for(size_t i = 0; i &lt; n; i++) {</p><p>      if(str1 == 0)</p><p>        return -1;</p><p>      else if(str2 == 0)</p><p>        return 1;</p><p>      else if(tolower(*str1) &lt; tolower(*str2))</p><p>        return -1;</p><p>      else if(tolower(*str1) &gt; tolower(*str2))</p><p>        return 1;</p><p>      assert(tolower(*str1) == tolower(*str2));</p><p>      str1++; str2++; // Compare the other chars</p><p>    }</p><p>    return 0;</p><p>  }</p><p>  static const char* find(const char* s1,</p><p>    size_t n, char c) {</p><p>    while(n-- &gt; 0)</p><p>      if(toupper(*s1) == toupper(c))</p><p>        return s1;</p><p>      else</p><p>        ++s1;</p><p>    return 0;</p><p>  }</p><p>};</p><empty-line/><p>typedef basic_string&lt;char, ichar_traits&gt; istring;</p><empty-line/><p>inline ostream&amp; operator&lt;&lt;(ostream&amp; os, const istring&amp; s) {</p><p>  return os &lt;&lt; string(s.c_str(), s.length());</p><p>}</p><p>#endif // ICHAR_TRAITS_H  ///:~</p><empty-line/><p>We provide a <strong>typedef</strong> named <strong>istring</strong> so that our class will act like an ordinary <strong>string</strong> in every way, except that it will make all comparisons without respect to case. For convenience, we’ve also provided an overloaded <strong>operator&lt;&lt;( )</strong> so that you can print <strong>istring</strong>s. Here’s an example:<sup>.</sup></p><p>//: C03:ICompare.cpp</p><p>#include &lt;cassert&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "ichar_traits.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  // The same letters except for case:</p><p>  istring first = "tHis";</p><p>  istring second = "ThIS";</p><p>  cout &lt;&lt; first &lt;&lt; endl;</p><p>  cout &lt;&lt; second &lt;&lt; endl;</p><p>  assert(first.compare(second) == 0);</p><p>  assert(first.find('h') == 1);</p><p>  assert(first.find('I') == 2);</p><p>  assert(first.find('x') == string::npos);</p><p>} ///:~</p><empty-line/><p>This is just a toy example, of course. To make <strong>istring</strong> fully equivalent to <strong>string</strong>, we’d have to create the other functions necessary to support the new <strong>istring</strong> type<sup>.</sup></p><p>The <strong>&lt;string&gt;</strong> header provides a wide string class via the following <strong>typedef</strong>:</p><p>typedef basic_string&lt;wchar_t&gt; wstring;</p><empty-line/><p>Wide string support also reveals itself in <emphasis>wide streams</emphasis> (<strong>wostream</strong> in place of <strong>ostream</strong>, also defined in <strong>&lt;iostream&gt;</strong>) and in the header <strong>&lt;cwctype&gt;</strong>, a wide-character version of <strong>&lt;cctype&gt;</strong>. This along with the <strong>wchar_t</strong> specialization of <strong>char_traits</strong> in the standard library allows us to do a wide-character version of <strong>ichar_traits</strong>:</p><p>//: C03:iwchar_traits.h</p><p>//{-bor}</p><p>//{-g++}</p><p>// Creating your own wide-character traits</p><p>#ifndef IWCHAR_TRAITS_H</p><p>#define IWCHAR_TRAITS_H</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cwctype&gt;</p><p>#include &lt;cmath&gt;</p><p>#include &lt;ostream&gt;</p><p>#include &lt;string&gt;</p><empty-line/><p>using std::towupper;</p><p>using std::towlower;</p><p>using std::wostream;</p><p>using std::wstring;</p><p>using std::char_traits;</p><p>using std::allocator;</p><p>using std::basic_string;</p><empty-line/><p>struct iwchar_traits : char_traits&lt;wchar_t&gt; {</p><p>  // We'll only change character-by-</p><p>  // character comparison functions</p><p>  static bool eq(wchar_t c1st, wchar_t c2nd) {</p><p>    return towupper(c1st) == towupper(c2nd);</p><p>  }</p><p>  static bool ne(wchar_t c1st, wchar_t c2nd) {</p><p>    return towupper(c1st) != towupper(c2nd);</p><p>  }</p><p>  static bool lt(wchar_t c1st, wchar_t c2nd) {</p><p>    return towupper(c1st) &lt; towupper(c2nd);</p><p>  }</p><p>  static int compare(const wchar_t* str1,</p><p>    const wchar_t* str2, size_t n) {</p><p>    for(size_t i = 0; i &lt; n; i++) {</p><p>      if(str1 == 0)</p><p>        return -1;</p><p>      else if(str2 == 0)</p><p>        return 1;</p><p>      else if(towlower(*str1) &lt; towlower(*str2))</p><p>        return -1;</p><p>      else if(towlower(*str1) &gt; towlower(*str2))</p><p>        return 1;</p><p>      assert(towlower(*str1) == towlower(*str2));</p><p>      str1++; str2++; // Compare the other wchar_ts</p><p>    }</p><p>    return 0;</p><p>  }</p><p>  static const wchar_t* find(const wchar_t* s1,</p><p>    size_t n, wchar_t c) {</p><p>    while(n-- &gt; 0)</p><p>      if(towupper(*s1) == towupper(c))</p><p>        return s1;</p><p>      else</p><p>        ++s1;</p><p>    return 0;</p><p>  }</p><p>};</p><empty-line/><p>typedef basic_string&lt;wchar_t, iwchar_traits&gt; iwstring;</p><empty-line/><p>inline wostream&amp; operator&lt;&lt;(wostream&amp; os,</p><p>  const iwstring&amp; s) {</p><p>  return os &lt;&lt; wstring(s.c_str(), s.length());</p><p>}</p><p>#endif // IWCHAR_TRAITS_H  ///:~</p><empty-line/><p>As you can see, this is mostly an exercise in placing a ‘w’ in the appropriate place in the source code. The test program looks like this:</p><p>//: C03:IWCompare.cpp</p><p>//{-g++}</p><p>#include &lt;cassert&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "iwchar_traits.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  // The same letters except for case:</p><p>  iwstring wfirst = L"tHis";</p><p>  iwstring wsecond = L"ThIS";</p><p>  wcout &lt;&lt; wfirst &lt;&lt; endl;</p><p>  wcout &lt;&lt; wsecond &lt;&lt; endl;</p><p>  assert(wfirst.compare(wsecond) == 0);</p><p>  assert(wfirst.find('h') == 1);</p><p>  assert(wfirst.find('I') == 2);</p><p>  assert(wfirst.find('x') == wstring::npos);</p><p>} ///:~</p><empty-line/><p>Unfortunately, some compilers still do not provide robust support for wide characters<sup>.</sup></p></section></section><section><title><p>A string application</p></title><p>If you’ve looked at the sample code in this book closely, you’ve noticed that certain tokens in the comments surround the code. These are used by a Python program that Bruce wrote to extract the code into files and set up makefiles for building the code. For example, a double-slash followed by a colon at the beginning of a line denotes the first line of a source file. The rest of the line contains information describing the file’s name and location and whether it should be only compiled rather than fully built into an executable file. For example, the first line in the previous program above contains the string <strong>C03:IWCompare.cpp</strong>, indicating that the file <strong>IWCompare.cpp</strong> should be extracted into the directory <strong>C03</strong><sup><strong>.</strong></sup></p><p>The last line of a source file contains a triple-slash followed by a colon and a tilde. If the first line has an exclamation point immediately after the colon, the first and last lines of the source code are not to be output to the file (this is for data-only files). (If you’re wondering why we’re avoiding showing you these tokens, it’s because we don’t want to break the code extractor when applied to the text of the book!)<sup>.</sup></p><p>Bruce’s Python program does a lot more than just extract code. If the token "<strong>{O}"</strong> follows the file name, its makefile entry will only be set up to compile the file and not to link it into an executable. (The Test Framework in Chapter 2 is built this way.) To link such a file with another source example, the target executable’s source file will contain an "<strong>{L}"</strong> directive, as in<sup>.</sup></p><p>//{L} ../TestSuite/Test</p><empty-line/><p>This section will present a program to just extract all the code so that you can compile and inspect it manually. You can use this program to extract all the code in this book by saving the document file as a text file<a l:href="#n36" type="note">[36]</a> (let’s call it TICV2.txt) and by executing something like the following on a shell command line:<sup>.</sup></p><p>C:&gt; extractCode TICV2.txt /TheCode</p><empty-line/><p>This command reads the text file <strong>TICV2.txt</strong> and writes all the source code files in subdirectories under the top-level directory <strong>/TheCode</strong>. The directory tree will look like the following:</p><p>TheCode/</p><p>   C0B/</p><p>   C01/</p><p>   C02/</p><p>   C03/</p><p>   C04/</p><p>   C05/</p><p>   C06/</p><p>   C07/</p><p>   C08/</p><p>   C09/</p><p>   C10/</p><p>   C11/</p><p>   TestSuite/</p><empty-line/><p>The source files containing the examples from each chapter will be in the corresponding directory<sup>.</sup></p><p>Here’s the program:</p><p>//: C03:ExtractCode.cpp</p><p>// Extracts code from text</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;cstdio&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><p>// Legacy non-standard C header for mkdir()</p><p>#ifdef __GNUC__</p><p>#include &lt;sys/stat.h&gt;</p><p>#elif defined(__BORLANDC__) || defined(_MSC_VER)</p><p>#include &lt;direct.h&gt;</p><p>#else</p><p>#error Compiler not supported</p><p>#endif</p><empty-line/><p>// Check to see if directory exists</p><p>// by attempting to open a new file</p><p>// for output within it.</p><p>bool exists(string fname) {</p><p>  size_t len = fname.length();</p><p>  if(fname[len-1] != '/' &amp;&amp; fname[len-1] != '\\')</p><p>    fname.append("/");</p><p>  fname.append("000.tmp");</p><p>  ofstream outf(fname.c_str());</p><p>  bool existFlag = outf;</p><p>  if (outf) {</p><p>    outf.close();</p><p>    remove(fname.c_str());</p><p>  }</p><p>  return existFlag;</p><p>}</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  // See if input file name provided</p><p>  if(argc == 1) {</p><p>    cerr &lt;&lt; "usage: extractCode file [dir]\n";</p><p>    exit(EXIT_FAILURE);</p><p>  }</p><p>  // See if input file exists</p><p>  ifstream inf(argv[1]);</p><p>  if(!inf) {</p><p>    cerr &lt;&lt; "error opening file: " &lt;&lt; argv[1] &lt;&lt; endl;</p><p>    exit(EXIT_FAILURE);</p><p>  }</p><p>  // Check for optional output directory</p><p>  string root("./");  // current is default</p><p>  if(argc == 3) {</p><p>    // See if output directory exists</p><p>    root = argv[2];</p><p>    if(!exists(root)) {</p><p>      cerr &lt;&lt; "no such directory: " &lt;&lt; root &lt;&lt; endl;</p><p>      exit(EXIT_FAILURE);</p><p>    }</p><p>    size_t rootLen = root.length();</p><p>    if(root[rootLen-1] != '/' &amp;&amp; root[rootLen-1] != '\\')</p><p>      root.append("/");</p><p>  }</p><p>  // Read input file line by line</p><p>  // checking for code delimiters</p><p>  string line;</p><p>  bool inCode = false;</p><p>  bool printDelims = true;</p><p>  ofstream outf;</p><p>  while (getline(inf, line)) {</p><p>    size_t findDelim = line.find("//" "/:~");</p><p>    if(findDelim != string::npos) {</p><p>      // Output last line and close file</p><p>      if (!inCode) {</p><p>        cerr &lt;&lt; "Lines out of order\n";</p><p>        exit(EXIT_FAILURE);</p><p>      }</p><p>      assert(outf);</p><p>      if (printDelims)</p><p>        outf &lt;&lt; line &lt;&lt; endl;</p><p>      outf.close();</p><p>      inCode = false;</p><p>      printDelims = true;</p><p>    } else {</p><p>      findDelim = line.find("//" ":");</p><p>      if(findDelim == 0) {</p><p>        // Check for '!' directive</p><p>        if(line[3] == '!') {</p><p>          printDelims = false;</p><p>          ++findDelim;  // To skip '!' for next search</p><p>        }</p><p>        // Extract subdirectory name, if any</p><p>        size_t startOfSubdir =</p><p>          line.find_first_not_of(" \t", findDelim+3);</p><p>        findDelim = line.find(':', startOfSubdir);</p><p>        if (findDelim == string::npos) {</p><p>          cerr &lt;&lt; "missing filename information\n" &lt;&lt; endl;</p><p>          exit(EXIT_FAILURE);</p><p>        }</p><p>        string subdir;</p><p>        if(findDelim &gt; startOfSubdir)</p><p>          subdir = line.substr(startOfSubdir,</p><p>                findDelim - startOfSubdir);</p><p>        // Extract file name (better be one!)</p><p>        size_t startOfFile = findDelim + 1;</p><p>        size_t endOfFile =</p><p>          line.find_first_of(" \t", startOfFile);</p><p>        if(endOfFile == startOfFile) {</p><p>          cerr &lt;&lt; "missing filename\n";</p><p>          exit(EXIT_FAILURE);</p><p>        }</p><p>        // We have all the pieces; build fullPath name</p><p>        string fullPath(root);</p><p>        if(subdir.length() &gt; 0)</p><p>          fullPath.append(subdir).append("/");</p><p>        assert(fullPath[fullPath.length()-1] == '/');</p><p>        if (!exists(fullPath))</p><p>#ifdef __GNUC__</p><p>          mkdir(fullPath.c_str(), 0);  // Create subdir</p><p>#else</p><p>          mkdir(fullPath.c_str());  // Create subdir</p><p>#endif</p><p>        fullPath.append(line.substr(startOfFile,</p><p>         endOfFile - startOfFile));</p><p>        outf.open(fullPath.c_str());</p><p>        if(!outf) {</p><p>          cerr &lt;&lt; "error opening " &lt;&lt; fullPath</p><p>&lt;&lt; " for output\n";</p><p>          exit(EXIT_FAILURE);</p><p>        }</p><p>        inCode = true;</p><p>        cout &lt;&lt; "Processing " &lt;&lt; fullPath &lt;&lt; endl;</p><p>        if(printDelims)</p><p>          outf &lt;&lt; line &lt;&lt; endl;</p><p>      }</p><p>      else if(inCode) {</p><p>        assert(outf);</p><p>        outf &lt;&lt; line &lt;&lt; endl;  // output middle code line</p><p>      }</p><p>    }</p><p>  }</p><p>  exit(EXIT_SUCCESS);</p><p>} ///:~</p><empty-line/><p>First, you’ll notice some conditional compilation directives. The <strong>mkdir( )</strong> function, which creates a directory in the file system, is defined by the POSIX<a l:href="#n37" type="note">[37]</a> standard in the header <strong>&lt;sys/stat.h&gt;</strong>. Unfortunately, many compilers still use a different header (<strong>&lt;direct.h&gt;</strong>). The respective signatures for <strong>mkdir( )</strong> also differ: POSIX specifies two arguments, the older versions just one. For this reason, there is more conditional compilation later in the program to choose the right call to <strong>mkdir( )</strong>. We normally don’t use conditional compilation in the examples in this book, but this particular program is too useful not to put a little extra work into, since you can use it to extract all the code with it<sup>.</sup></p><p>The <strong>exists( )</strong> function in <strong>ExtractCode.cpp</strong> tests whether a directory exists by opening a temporary file in it. If the open fails, the directory doesn’t exist. You remove a file by sending its name as a <strong>char*</strong> to <strong>std::remove( )</strong><sup><strong>.</strong></sup></p><p>The main program validates the command-line arguments and then reads the input file a line at a time, looking for the special source code delimiters. The Boolean flag <strong>inCode</strong> indicates that the program is in the middle of a source file, so lines should be output. The <strong>printDelims</strong> flag will be true if the opening token is not followed by an exclamation point; otherwise the first and last lines are not written. It is important to check for the closing delimiter first, because the start token is a subset of it, and searching for the start token first would return a successful find for both cases. If we encounter the closing token, we verify that we are in the middle of processing a source file; otherwise, something is wrong with the way the delimiters are laid out in the text file. If <strong>inCode</strong> is true, all is well, and we (optionally) write the last line and close the file. When the opening token is found, we parse the directory and file name components and open the file. The following <strong>string</strong>-related functions were used in this example: <strong>length( )</strong>, <strong>append( )</strong>, <strong>getline( )</strong>, <strong>find( )</strong> (two versions), <strong>find_first_not_of( )</strong>, <strong>substr( )</strong>, <strong>find_first_of( )</strong>, <strong>c_str( )</strong>, and, of course, <strong>operator&lt;&lt;( )</strong><sup><strong>.</strong></sup></p><p>We also use a standard C technique for reporting program status to the calling context by returning different values from <strong>main( )</strong>. It is portable to use the statement <strong>return 0;</strong> to indicate success, but there is no portable value to indicate failure. For this reason we use the macro declared for this very purpose in <strong>&lt;cstdlib&gt;</strong>: <strong>EXIT_FAILURE</strong>. As a matter of consistency, whenever we use <strong>EXIT_FAILURE</strong> we also use <strong>EXIT_SUCCESS</strong>, even though the latter is always defined as zero<sup>.</sup></p></section><section><title><p>Summary</p></title><p>C++ string objects provide developers with a number of great advantages over their C counterparts. For the most part, the <strong>string</strong> class makes referring to strings through the use of character pointers unnecessary. This eliminates an entire class of software defects that arise from the use of uninitialized and incorrectly valued pointers. C++ strings dynamically and transparently grow their internal data storage space to accommodate increases in the size of the string data. This means that when the data in a string grows beyond the limits of the memory initially allocated to it, the string object will make the memory management calls that take space from and return space to the heap. Consistent allocation schemes prevent memory leaks and have the potential to be much more efficient than "roll your own" memory management<sup>.</sup></p><p>The <strong>string</strong> class member functions provide a fairly comprehensive set of tools for creating, modifying, and searching in strings. String comparisons are always case sensitive, but you can work around this by copying string data to C-style null-terminated strings and using case-insensitive string comparison functions, temporarily converting the data held in string objects to a single case, or by creating a case-insensitive string class that overrides the character traits used to create the <strong>basic_string</strong> object<sup>.</sup></p></section><section><title><p>Exercises</p></title><p>             1.             Write a program that reverses the order of the characters in a string.</p><p>         18.             A palindrome is a word or group of words that read the same forward and backward. For example "madam" or "wow." Write a program that takes a string argument from the command line and prints whether the string was a palindrome or not.</p><p>         19.             Make your program from exercise 2 return <strong>true</strong> even if symmetric letters differ in case. For example, "Civic" would still return <strong>true</strong> although the first letter is capitalized.</p><p>        20.             Make your program from exercise 3 report true even if the string contains punctuation and spaces. For example "Able was I, ere I saw Elba." would report <strong>true</strong>.</p><p>         21.             Using the following strings and only <strong>char</strong>s (no string literals or magic numbers):</p><p>string one("I walked down the canyon with the moving mountain bikers.");</p><p>string two("The bikers passed by me too close for comfort."); string three("I went hiking instead.")</p><p>         produce the following sentence:</p><p>"I moved down the canyon with the mountain bikers. The mountain bikers passed by me too close for comfort. So I went hiking instead."</p><p>        22.             Write a program named <strong>replace</strong> that takes three command-line arguments representing an input text file, a string to replace (call it <strong>from</strong>), and a replacement string (call it <strong>to</strong>). The program should write a new file to standard output with all occurrences of <strong>from</strong> replaced by <strong>to</strong>.</p><p>        23.             Repeat the previous exercise but replace all instances of <strong>from</strong> regardless of case.</p><empty-line/></section></section><section><title><p>4: Iostreams</p></title><section><p>You can do much more with the general I/O problem than just take standard I/O and turn it into a class.</p><p>Wouldn’t it be nice if you could make all the usual "receptacles"—standard I/O, files, and even blocks of memory—look the same so that you need to remember only one interface? That’s the idea behind iostreams. They’re much easier, safer, and sometimes even more efficient than the assorted functions from the Standard C <strong>stdio</strong> library<sup>.</sup></p><p>The iostreams classes are usually the first part of the C++ library that new C++ programmers learn to use. This chapter discusses how iostreams are an improvement over C’s <strong>stdio</strong> facilities and explores the behavior of file and string streams in addition to the standard console streams<sup>.</sup></p></section><section><title><p>Why iostreams?</p></title><p>You might wonder what’s wrong with the good old C library. Why not "wrap" the C library in a class and be done with it? Indeed, this is the perfect thing to do in some situations. For example, suppose you want to make sure the file represented by a <strong>stdio FILE</strong> pointer is always safely opened and properly closed, without having to rely on the user to remember to call the <strong>close( )</strong> function. The following program is such an attempt<sup>.</sup></p><p>//: C04:FileClass.h</p><p>// stdio files wrapped</p><p>#ifndef FILECLASS_H</p><p>#define FILECLASS_H</p><p>#include &lt;cstdio&gt;</p><p>#include &lt;stdexcept&gt;</p><empty-line/><p>class FileClass {</p><p>  std::FILE* f;</p><p>public:</p><p>  struct FileClassError : std::runtime_error {</p><p>  public:</p><p>    FileClassError(const char* msg)</p><p>      : std::runtime_error(msg) {}</p><p>  };</p><p>  FileClass(const char* fname, const char* mode = "r");</p><p>  ~FileClass();</p><p>  std::FILE* fp();</p><p>};</p><p>#endif // FILECLASS_H ///:~</p><empty-line/><p>When you perform file I/O in C, you work with a naked pointer to a FILE <strong>struct</strong>, but this class wraps around the pointer and guarantees it is properly initialized and cleaned up using the constructor and destructor. The second constructor argument is the file mode, which defaults to "r" for "read."<sup>.</sup></p><p>To fetch the value of the pointer to use in the file I/O functions, you use the <strong>fp( )</strong> access function. Here are the member function definitions:<sup>.</sup></p><p>//: C04:FileClass.cpp {O}</p><p>// FileClassImplementation</p><p>#include "FileClass.h"</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;cstdio&gt;</p><p>using namespace std;</p><empty-line/><p>FileClass::FileClass(const char* fname, const char* mode) {</p><p>  if((f = fopen(fname, mode)) == 0)</p><p>    throw FileClassError("Error opening file");</p><p>}</p><empty-line/><p>FileClass::~FileClass() { fclose(f); }</p><empty-line/><p>FILE* FileClass::fp() { return f; } ///:~</p><empty-line/><p>The constructor calls <strong>fopen( )</strong>, as you would normally do, but it also ensures that the result isn’t zero, which indicates a failure upon opening the file. If the file does not open as expected, an exception is thrown<sup>.</sup></p><p>The destructor closes the file, and the access function <strong>fp( ) </strong>returns <strong>f</strong>. Here’s a simple example using <strong>class FileClass</strong>:<sup>.</sup></p><p>//: C04:FileClassTest.cpp</p><p>// Tests FileClass</p><p>//{L} FileClass</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "FileClass.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  try {</p><p>    FileClass f("FileClassTest.cpp");</p><p>    const int BSIZE = 100;</p><p>    char buf[BSIZE];</p><p>    while(fgets(buf, BSIZE, f.fp()))</p><p>      fputs(buf, stdout);</p><p>  }</p><p>  catch(FileClass::FileClassError&amp; e) {</p><p>    cout &lt;&lt; e.what() &lt;&lt; endl;</p><p>    return EXIT_FAILURE;</p><p>  }</p><p>  return EXIT_SUCCESS;</p><p>} // File automatically closed by destructor</p><p>///:~</p><empty-line/><p>You create the <strong>FileClass</strong> object and use it in normal C file I/O function calls by calling <strong>fp( )</strong>. When you’re done with it, just forget about it; the file is closed by the destructor at the end of its scope<sup>.</sup></p><p>Even though the <strong>FILE</strong> pointer is private, it isn’t particularly safe because <strong>fp( )</strong> retrieves it. Since the only effect seems to be guaranteed initialization and cleanup, why not make it public or use a <strong>struct</strong> instead? Notice that while you can get a copy of <strong>f</strong> using <strong>fp( )</strong>, you cannot assign to <strong>f</strong>— that’s completely under the control of the class. Of course, after capturing the pointer returned by <strong>fp( )</strong>, the client programmer can still assign to the structure elements or even close it, so the safety is in guaranteeing a valid <strong>FILE</strong> pointer rather than proper contents of the structure<sup>.</sup></p><p>If you want complete safety, you must prevent the user from directly accessing the <strong>FILE</strong> pointer. Some version of all the normal file I/O functions must show up as class members so that everything you can do with the C approach is available in the C++ class:<sup>.</sup></p><p>//: C04:Fullwrap.h</p><p>// Completely hidden file IO</p><p>#ifndef FULLWRAP_H</p><p>#define FULLWRAP_H</p><empty-line/><p>class File {</p><p>  std::FILE* f;</p><p>  std::FILE* F(); // Produces checked pointer to f</p><p>public:</p><p>  File(); // Create object but don't open file</p><p>  File(const char* path,</p><p>       const char* mode = "r");</p><p>  ~File();</p><p>  int open(const char* path,</p><p>           const char* mode = "r");</p><p>  int reopen(const char* path,</p><p>             const char* mode);</p><p>  int getc();</p><p>  int ungetc(int c);</p><p>  int putc(int c);</p><p>  int puts(const char* s);</p><p>  char* gets(char* s, int n);</p><p>  int printf(const char* format, ...);</p><p>  size_t read(void* ptr, size_t size,</p><p>              size_t n);</p><p>  size_t write(const void* ptr,</p><p>size_t size, size_t n);</p><p>  int eof();</p><p>  int close();</p><p>  int flush();</p><p>  int seek(long offset, int whence);</p><p>  int getpos(fpos_t* pos);</p><p>  int setpos(const fpos_t* pos);</p><p>  long tell();</p><p>  void rewind();</p><p>  void setbuf(char* buf);</p><p>  int setvbuf(char* buf, int type, size_t sz);</p><p>  int error();</p><p>  void clearErr();</p><p>};</p><p>#endif // FULLWRAP_H ///:~</p><empty-line/><p>This class contains almost all the file I/O functions from <strong>&lt;cstdio&gt;</strong>. (<strong>vfprintf( )</strong> is missing; it is used to implement the <strong>printf( )</strong> member function.)<sup>.</sup></p><p><strong>File</strong> has the same constructor as in the previous example, and it also has a default constructor. The default constructor is important if you want to create an array of <strong>File</strong> objects or use a <strong>File</strong> object as a member of another class in which the initialization doesn’t happen in the constructor, but some time after the enclosing object is created<sup>.</sup></p><p>The default constructor sets the private <strong>FILE</strong> pointer <strong>f</strong> to zero. But now, before any reference to <strong>f</strong>, its value must be checked to ensure it isn’t zero. This is accomplished with <strong>F( )</strong>, which is <strong>private</strong> because it is intended to be used only by other member functions. (We don’t want to give the user direct access to the underlying <strong>FILE</strong> structure in this class.)<a l:href="#n38" type="note">[38]</a></p><p>This approach is not a terrible solution by any means. It’s quite functional, and you could imagine making similar classes for standard (console) I/O and for in-core formatting (reading/writing a piece of memory rather than a file or the console)<sup>.</sup></p><p>The big stumbling block is the runtime interpreter used for the variable argument list functions. This is the code that parses your format string at runtime and grabs and interprets arguments from the variable argument list. It’s a problem for four reasons<sup>.</sup></p><p>1.Even if you use only a fraction of the functionality of the interpreter, the whole thing gets loaded into your executable. So if you say printf("%c", 'x');, you’ll get the whole package, including the parts that print floating-point numbers and strings. There’s no standard option for reducing the amount of space used by the program<sup>.</sup></p><p>2.Because the interpretation happens at runtime, you can’t get rid of a performance overhead. It’s frustrating because all the information is <emphasis>there</emphasis> in the format string at compile time, but it’s not evaluated until runtime. However, if you could parse the arguments in the format string at compile time, you could make direct function calls that have the potential to be much faster than a runtime interpreter (although the <strong>printf( )</strong> family of functions is usually quite well optimized)<sup>.</sup></p><p>3.A worse problem is that the format string is not evaluated until runtime: there can be no compile-time error checking. You’re probably familiar with this problem if you’ve tried to find bugs that came from using the wrong number or type of arguments in a <strong>printf( )</strong> statement. C++ makes a big deal out of compile-time error checking to find errors early and make your life easier. It seems a shame to throw type safety away for an I/O library, especially because I/O is used a lot<sup>.</sup></p><p>4.For C++, the most crucial problem is that the <strong>printf( )</strong> family of functions is not particularly extensible. They’re really designed to handle only the four basic data types in C (<strong>char</strong>, <strong>int</strong>, <strong>float</strong>, <strong>double</strong>, <strong>wchar_t</strong>, <strong>char*</strong>, <strong>wchar_t*</strong>, and <strong>void*)</strong> and their variations. You might think that every time you add a new class, you could add overloaded <strong>printf( )</strong> and <strong>scanf( )</strong> functions (and their variants for files and strings), but remember, overloaded functions must have different types in their argument lists, and the <strong>printf( )</strong> family hides its type information in the format string and in the variable argument list. For a language such as C++, whose goal is to be able to easily add new data types, this is an ungainly restriction<sup>.</sup></p></section><section><title><p>Iostreams to the rescue</p></title><section><p>All these issues make it clear that one of the first priorities for the standard class libraries for C++ should handle I/O. Because "hello, world" is the first program just about everyone writes in a new language, and because I/O is part of virtually every program, the I/O library in C++ must be particularly easy to use. It also has the much greater challenge that it must accommodate any new class. Thus, its constraints require that this foundation class library be a truly inspired design. In addition to gaining a great deal of leverage and clarity in your dealings with I/O and formatting, you’ll also see in this chapter how a really powerful C++ library can work<sup>.</sup></p></section><section><title><p>Inserters and extractors</p></title><p>A <emphasis>stream</emphasis> is an object that transports and formats characters of a fixed width. You can have an input stream (via descendants of the <strong>istream</strong> class), an output stream (with <strong>ostream</strong> objects), or a stream that does both simultaneously (with objects derived from <strong>iostream</strong>). The iostreams library provides different types of such classes: <strong>ifstream</strong>, <strong>ofstream</strong>, and <strong>fstream</strong> for files, and <strong>istringstream</strong>, <strong>ostringstream</strong>, and <strong>stringstream</strong> for interfacing with the Standard C++ <strong>string</strong> class. All these stream classes have nearly identical interfaces, so you can use streams in a uniform manner, whether you’re working with a file, standard I/O, a region of memory, or a <strong>string</strong> object. The single interface you learn also works for extensions added to support new classes. Some functions implement your formatting commands, and some functions read and write characters without formatting<sup>.</sup></p><p>The stream classes mentioned earlier are actually template specializations,<a l:href="#n39" type="note">[39]</a> much like the standard <strong>string</strong> class is a specialization of the <strong>basic_string</strong> template. The basic classes in the iostreams inheritance hierarchy are shown in the following figure<sup>.</sup></p><p><image l:href="#1"/></p><p>The <strong>ios_base</strong> class declares everything that is common to all streams, independent of the type of character the stream handles. These declarations are mostly constants and functions to manage them, some of which you’ll see throughout this chapter. The rest of the classes are templates that have the underlying character type as a parameter. The <strong>istream</strong> class, for example, is defined as follows:<sup>.</sup></p><p>typedef basic_istream&lt;char&gt; istream;</p><empty-line/><p>All the classes mentioned earlier are defined via similar type definitions. There are also type definitions for all stream classes using <strong>wchar_t</strong> (the wide character type discussed in Chapter 3) instead of <strong>char</strong>. We’ll look at these at the end of this chapter. The <strong>basic_ios</strong> template defines functions common to both input and output, but that depends on the underlying character type (we won’t use these much). The template <strong>basic_istream</strong> defines generic functions for input, and <strong>basic_ostream</strong> does the same for output. The classes for file and string streams introduced later add functionality for their specific stream types<sup>.</sup></p><p>In the iostreams library, two operators are overloaded to simplify the use of iostreams. The operator <strong>&lt;&lt;</strong> is often referred to as an <emphasis>inserter</emphasis> for iostreams, and the operator <strong>&gt;&gt;</strong> is often referred to as an <emphasis>extractor</emphasis><sup><emphasis>.</emphasis></sup></p><p>Extractors parse the information that’s expected by the destination object according to its type. To see an example of this, you can use the <strong>cin</strong> object, which is the iostream equivalent of <strong>stdin</strong> in C, that is, redirectable standard input. This object is predefined whenever you include the <strong>&lt;iostream&gt; </strong>header<sup>.</sup></p><p>  int i;</p><p>  cin &gt;&gt; i;</p><empty-line/><p>  float f;</p><p>  cin &gt;&gt; f;</p><empty-line/><p>  char c;</p><p>  cin &gt;&gt; c;</p><empty-line/><p>  char buf[100];</p><p>  cin &gt;&gt; buf;</p><empty-line/><p>There’s an overloaded <strong>operator &gt;&gt;</strong> for every built-in data type. You can also overload your own, as you’ll see later<sup>.</sup></p><p>To find out what you have in the various variables, you can use the <strong>cout</strong> object (corresponding to standard output; there’s also a <strong>cerr</strong> object corresponding to standard error) with the inserter <strong>&lt;&lt;</strong>:<sup>.</sup></p><p>  cout &lt;&lt; "i = ";</p><p>  cout &lt;&lt; i;</p><p>  cout &lt;&lt; "\n";</p><p>  cout &lt;&lt; "f = ";</p><p>  cout &lt;&lt; f;</p><p>  cout &lt;&lt; "\n";</p><p>  cout &lt;&lt; "c = ";</p><p>  cout &lt;&lt; c;</p><p>  cout &lt;&lt; "\n";</p><p>  cout &lt;&lt; "buf = ";</p><p>  cout &lt;&lt; buf;</p><p>  cout &lt;&lt; "\n";</p><empty-line/><p>This is notably tedious and doesn’t seem like much of an improvement over <strong>printf( )</strong>, despite improved type checking. Fortunately, the overloaded inserters and extractors are designed to be chained together into a more complicated expression that is much easier to write (and read):<sup>.</sup></p><p>  cout &lt;&lt; "i = " &lt;&lt; i &lt;&lt; endl;</p><p>  cout &lt;&lt; "f = " &lt;&lt; f &lt;&lt; endl;</p><p>  cout &lt;&lt; "c = " &lt;&lt; c &lt;&lt; endl;</p><p>  cout &lt;&lt; "buf = " &lt;&lt; buf &lt;&lt; endl;</p><empty-line/><p>Defining inserters and extractors for your own classes is just a matter of overloading the associated operators to do the right things, namely:</p><p>·         Make the first parameter a non-<strong>const</strong> reference to the stream (<strong>istream</strong> for input, <strong>ostream</strong> for output)</p><p>·         Perform the operation by insert/extracting data to/from the stream (by processing the components of the object, of course)</p><p>·         Return a reference to the stream</p><p>The stream should be non-<strong>const</strong> because processing stream data changes the state of the stream. By returning the stream, you allow for chaining stream operations in a single statement, as shown earlier<sup>.</sup></p><p>As an example, consider how to output the representation of a <strong>Date</strong> object in MM-DD-YYYY format. The following inserter does the job:</p><p>ostream&amp; operator&lt;&lt;(ostream&amp; os, const Date&amp; d) {</p><p>  char fillc = os.fill('0');</p><p>  os &lt;&lt; setw(2) &lt;&lt; d.getMonth() &lt;&lt; '-'</p><p>     &lt;&lt; setw(2) &lt;&lt; d.getDay() &lt;&lt; '-'</p><p>     &lt;&lt; setw(4) &lt;&lt; setfill(fillc) &lt;&lt; d.getYear();</p><p>  return os;</p><p>}</p><empty-line/><p>This function cannot be a member of the <strong>Date</strong> class, of course, because the left operand of the <strong>&lt;&lt;</strong> operator must be the output stream. The <strong>fill( )</strong> member function of <strong>ostream</strong> changes the padding character used when the width of an output field, determined by the <emphasis>manipulator</emphasis><strong>setw( )</strong>, is greater than needed for the data. We use a ‘0’ character so that months before October will display with a leading zero, such as "09" for September. The <strong>fill( )</strong> function also returns the previous fill character (which defaults to a single space) so that we can restore it later with the manipulator <strong>setfill( )</strong>. We discuss manipulators in depth later in this chapter<sup>.</sup></p><p>Extractors require a little more care because things sometimes go wrong with input data. The way to signal a stream error is to set the stream’s <emphasis>fail bit</emphasis>, as follows:</p><p>istream&amp; operator&gt;&gt;(istream&amp; is, Date&amp; d) {</p><p>  is &gt;&gt; d.month;</p><p>  char dash;</p><p>  is &gt;&gt; dash;</p><p>  if (dash != '-')</p><p>    is.setstate(ios::failbit);</p><p>  is &gt;&gt; d.day;</p><p>  is &gt;&gt; dash;</p><p>  if (dash != '-')</p><p>    is.setstate(ios::failbit);</p><p>  is &gt;&gt; d.year;</p><p>  return is;</p><p>}</p><empty-line/><p>When an error bit is set in a stream, all further streams operations are ignored until the stream is restored to a good state (explained shortly). That’s why the code above continues extracting even if <strong>ios::failbit</strong> gets set. This implementation is somewhat forgiving in that it allows white space between the numbers and dashes in a date string (because the <strong>&gt;&gt;</strong> operator skips white space by default when reading built-in types). The following are valid date strings for this extractor:<sup>.</sup></p><p>"08-10-2003"</p><p>"8-10-2003"</p><p>"08 - 10 - 2003"</p><empty-line/><p>but these are not:</p><p>"A-10-2003"    // No alpha characters allowed</p><p>"08%10/2003"   // Only dashes allowed as a delimiter</p><empty-line/><p>We’ll discuss stream state in more depth in the section "Handling stream errors" later in this chapter<sup>.</sup></p></section><section><title><p>Common usage</p></title><p>As the <strong>Date</strong> extractor illustrated, you must be on guard for erroneous input. If the input produces an unexpected value, the process is skewed, and it’s difficult to recover. In addition, formatted input defaults to white space delimiters. Consider what happens when we collect the code fragments from earlier in this chapter into a single program:<sup>.</sup></p><p>//: C04:Iosexamp.cpp</p><p>// Iostream examples</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  int i;</p><p>  cin &gt;&gt; i;</p><empty-line/><p>  float f;</p><p>  cin &gt;&gt; f;</p><empty-line/><p>  char c;</p><p>  cin &gt;&gt; c;</p><empty-line/><p>  char buf[100];</p><p>  cin &gt;&gt; buf;</p><empty-line/><p>  cout &lt;&lt; "i = " &lt;&lt; i &lt;&lt; endl;</p><p>  cout &lt;&lt; "f = " &lt;&lt; f &lt;&lt; endl;</p><p>  cout &lt;&lt; "c = " &lt;&lt; c &lt;&lt; endl;</p><p>  cout &lt;&lt; "buf = " &lt;&lt; buf &lt;&lt; endl;</p><empty-line/><p>  cout &lt;&lt; flush;</p><p>  cout &lt;&lt; hex &lt;&lt; "0x" &lt;&lt; i &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>and give it the following input:<sup>.</sup></p><p>12 1.4 c this is a test</p><empty-line/><p>We expect the same output as if we gave it:</p><p>12</p><p>1.4</p><p>c</p><p>this is a test</p><empty-line/><p>but the output is, somewhat unexpectedly</p><p>i = 12</p><p>f = 1.4</p><p>c = c</p><p>buf = this</p><p>0xc</p><empty-line/><p>Notice that <strong>buf</strong> got only the first word because the input routine looked for a space to delimit the input, which it saw after "this." In addition, if the continuous input string is longer than the storage allocated for <strong>buf</strong>, we overrun the buffer<sup>.</sup></p><p>In practice, you’ll usually want to get input from interactive programs a line at a time as a sequence of characters, scan them, and then perform conversions once they’re safely in a buffer. This way you don’t have to worry about the input routine choking on unexpected data<sup>.</sup></p><p>Another thing to consider is the whole concept of a command-line interface. This made sense in the past when the console was little more than a glass typewriter, but the world is rapidly changing to one in which the graphical user interface (GUI) dominates. What is the meaning of console I/O in such a world? It makes much more sense to ignore <strong>cin</strong> altogether, other than for simple examples or tests, and take the following approaches:<sup>.</sup></p><p>1.If your program requires input, read that input from a file—you’ll soon see that it’s remarkably easy to use files with iostreams. Iostreams for files still works fine with a GUI<sup>.</sup></p><p>2.Read the input without attempting to convert it, as we just suggested. When the input is some place where it can’t foul things up during conversion, you can safely scan it<sup>.</sup></p><p>3.Output is different. If you’re using a GUI, <strong>cout</strong> doesn’t necessarily work, and you must send it to a file (which is identical to sending it to <strong>cout</strong>) or use the GUI facilities for data display. Otherwise it often makes sense to send it to <strong>cout</strong>. In both cases, the output formatting functions of iostreams are highly useful<sup>.</sup></p><p>Another common practice saves compile time on large projects. Consider, for example, how you would declare the Date stream operators introduced earlier in the chapter in a header file. You only need to include the prototypes for the functions, so it’s not really necessary to include the entire <strong>&lt;iostream&gt;</strong> header in <strong>Date.h</strong>. The standard practice is to only declare classes, something like this:<sup>.</sup></p><p>class ostream;</p><empty-line/><p>This is an age-old technique for separating interface from implementation and is often called a <strong>forward declaration</strong> (and <strong>ostream</strong> at this point would be considered an <emphasis>incomplete type</emphasis>, since the class definition has not yet been seen by the compiler)<sup>.</sup></p><p>This will not work as is, however, for two reasons:</p><p>1.       The stream classes are defined in the <strong>std</strong> namespace.</p><p>2.      They are templates.</p><p>The proper declaration would be:</p><p>namespace std {</p><p>  template&lt;class charT, class traits = char_traits&lt;charT&gt; &gt;</p><p>    class basic_ostream;</p><p>  typedef basic_ostream&lt;char&gt; ostream;</p><p>}</p><empty-line/><p>(As you can see, like the <strong>string</strong> class, the streams classes use the character traits classes mentioned in Chapter 3). Since it would be terribly tedious to type all that for every stream class you want to reference, the standard provides a header that does it for you: <strong>&lt;iosfwd&gt;</strong>. The <strong>Date</strong> header would then look something like this:<sup>.</sup></p><p>// Date.h</p><p>#include &lt;iosfwd&gt;</p><p>class Date {</p><p>  friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp;,</p><p>                   const Date&amp;);</p><p>  friend std::istream&amp; operator&gt;&gt;(std::istream&amp;, Date&amp;);</p><p>  // etc<sup>.</sup></p><empty-line/></section><section><title><p>Line-oriented input</p></title><section><p>To grab input a line at a time, you have three choices:</p><p>The member function <strong>get( )</strong></p><p>The member function <strong>getline( )</strong></p><p>The global function <strong>getline( )</strong> defined in the <strong>&lt;string&gt;</strong> header</p><p>The first two functions take three arguments:</p><p>A pointer to a character buffer in which to store the result</p><p>The size of that buffer (so it’s not overrun)</p><p>The terminating character, to know when to stop reading input</p><p>The terminating character has a default value of <strong>'\n'</strong>, which is what you’ll usually use. Both functions store a zero in the result buffer when they encounter the terminating character in the input<sup>.</sup></p><p>So what’s the difference? Subtle, but important: <strong>get( )</strong> stops when it <emphasis>sees</emphasis> the delimiter in the input stream, but it doesn’t extract it from the input stream. Thus, if you did another <strong>get( )</strong> using the same delimiter, it would immediately return with no fetched input. (Presumably, you either use a different delimiter in the next <strong>get( )</strong> statement or a different input function.) The <strong>getline( ) </strong>function, on the other hand, extracts the delimiter from the input stream, but still doesn’t store it in the result buffer<sup>.</sup></p><p>The <strong>getline( )</strong> function defined in <strong>&lt;string&gt;</strong> is convenient. It is not a member function, but rather a stand-alone function declared in the namespace <strong>std</strong>. It takes only two non-default arguments, the input stream and the <strong>string</strong> object to populate. Like its namesake, it reads characters until it encounters the first occurrence of the delimiter (<strong>'\n'</strong> by default) and consumes and discards the delimiter. The advantage of this function is that it reads into a <strong>string</strong> object, so you don’t have to worry about buffer size<sup>.</sup></p><p>Generally, when you’re processing a text file that you read a line at a time, you’ll want to use one of the <strong>getline( )</strong> functions<sup>.</sup></p></section><section><section><title><p>Overloaded versions of get( )</p></title><p>The <strong>get( )</strong> function also comes in three other overloaded versions: one with no arguments that returns the next character, using an <strong>int</strong> return value; one that stuffs a character into its <strong>char</strong> argument, using a <emphasis>reference</emphasis>; and one that stores directly into the underlying buffer structure of another iostream object. The latter is explored later in the chapter<sup>.</sup></p></section><section><title><p>Reading raw bytes</p></title><p>If you know exactly what you’re dealing with and want to move the bytes directly into a variable, an array, or a structure in memory, you can use the unformatted I/O function <strong>read( )</strong>. The first argument is a pointer to the destination memory, and the second is the number of bytes to read. This is especially useful if you’ve previously stored the information to a file, for example, in binary form using the complementary <strong>write( )</strong> member function for an output stream (using the same compiler, of course). You’ll see examples of all these functions later<sup>.</sup></p></section></section></section></section><section><title><p>Handling stream errors</p></title><section><p>The <strong>Date</strong> extractor shown earlier sets a stream’s fail bit under certain conditions. How does the user know when such a failure occurs? You can detect stream errors by either calling certain stream member functions to see if an error state has occurred, or if you don’t care what the particular error was, you can just evaluate the stream in a Boolean context. Both techniques derive from the state of a stream’s error bits<sup>.</sup></p></section><section><section><section><title><p>Stream state</p></title><p>The <strong>ios_base</strong> class, from which <strong>ios</strong> derives,<a l:href="#n40" type="note">[40]</a> defines four flags that you can use to test the state of a stream:</p><empty-line/><table><tr align="left"><td align="left" valign="top">Flag</td><td align="left" valign="top">Meaning</td></tr><tr align="left"><td align="left" valign="top"><strong>badbit</strong></td><td align="left" valign="top">Some fatal (perhaps physical) error occurred. The stream should be considered unusable.</td></tr><tr align="left"><td align="left" valign="top"><strong>eofbit</strong></td><td align="left" valign="top">End-of-input has occurred (either by encountering the physical end of a file stream or by the user terminating a console stream, such as with Ctrl-Z or Ctrl&#x2011;D).</td></tr><tr align="left"><td align="left" valign="top"><strong>failbit</strong></td><td align="left" valign="top">An I/O operation failed, most likely because of invalid data (e.g., letters were found when trying to read a number). The stream is still usable. The failbit flag is also set when end-of-input occurs.</td></tr><tr align="left"><td align="left" valign="top"><strong>goodbit</strong></td><td align="left" valign="top">All is well; no errors. End-of-input has not yet occurred.</td></tr></table><empty-line/><p>You can test whether any of these conditions have occurred by calling corresponding member functions that return a Boolean value indicating whether any of these have been set. The <strong>good( )</strong> stream member function returns true if none of the other three bits are set. The <strong>eof( )</strong> function returns true if <strong>eofbit</strong> is set, which happens with an attempt to read from a stream that has no more data (usually a file). Because end-of-input happens in C++ when trying to read past the end of the physical medium, <strong>failbit</strong> is also set to indicate that the "expected" data was not successfully read. The <strong>fail( )</strong> function returns true if <emphasis>either</emphasis><strong>failbit</strong> or <strong>badbit</strong> is set, and <strong>bad( )</strong> returns true only if the <strong>badbit</strong> is set<sup>.</sup></p><p>Once any of the error bits in a stream’s state are set, they remain set, which is not always what you want. When reading a file for example, you might want to reposition to an earlier place in the file before end-of-file occurred. Just moving the file pointer doesn’t automatically reset <strong>eofbit</strong> or <strong>failbit</strong>; you have to do it yourself with the <strong>clear( )</strong> function, like this:<sup>.</sup></p><p>myStream.clear();    // Clears all error bits</p><empty-line/><p>After calling <strong>clear( )</strong>, <strong>good( )</strong> will return <strong>true</strong> if called immediately. As you saw in the <strong>Date</strong> extractor earlier, the <strong>setstate( )</strong> function sets the bits you pass it. It turns out that <strong>setstate( )</strong> doesn’t affect any other bits—if they’re already set, they stay set. If you want to set certain bits but at the same time reset all the rest, you can call an overloaded version of <strong>clear( )</strong>, passing it a bitwise expression representing the bits you want to set, as in:<sup>.</sup></p><p>myStream.clear(ios::failbit | ios::eofbit);</p><empty-line/><p>Most of the time you won’t be interested in checking the stream state bits individually. Usually you just want to know if everything is okay. This is the case when you read a file from beginning to end; you just want to know when the input data is exhausted. In cases such as these, a conversion operator is defined for <strong>void*</strong> that is automatically called when a stream occurs in a Boolean expression. To read a stream until end-of-input using this idiom looks like the following:<sup>.</sup></p><p>int i;</p><p>while (myStream &gt;&gt; i)</p><p>  cout &lt;&lt; i &lt;&lt; endl;</p><empty-line/><p>Remember that <strong>operator&gt;&gt;( )</strong> returns its stream argument, so the <strong>while</strong> statement above tests the stream as a Boolean expression. This particular example assumes that the input stream <strong>myStream</strong> contains integers separated by white space. The function <strong>ios_base::operator void*( )</strong> simply calls <strong>good( )</strong> on its stream and returns the result.<a l:href="#n41" type="note">[41]</a> Because most stream operations return their stream, using this idiom is convenient<sup>.</sup></p></section><section><title><p>Streams and exceptions</p></title><p>Iostreams existed as part of C++ long before there were exceptions, so checking stream state manually was just the way things were done. For backward compatibility, this is still the status quo, but iostreams can throw exceptions instead. The <strong>exceptions( )</strong> stream member function takes a parameter representing the state bits for which you want exceptions to be thrown. Whenever the stream encounters such a state, it throws an exception of type <strong>std::ios_base::failure</strong>, which inherits from <strong>std::exception</strong><sup><strong>.</strong></sup></p><p>Although you can trigger a failure exception for any of the four stream states, it’s not necessarily a good idea to enable exceptions for all of them. As Chapter 1 explains, use exceptions for truly exceptional conditions, but end-of-file is not only <emphasis>not</emphasis> exceptional—it’s <emphasis>expected</emphasis>! For that reason, you might want to enable exceptions only for the errors represented by <strong>badbit</strong>, which you would do like this:<sup>.</sup></p><p>myStream.exceptions(ios::badbit);</p><empty-line/><p>You enable exceptions on a stream-by-stream basis, since <strong>exceptions( )</strong> is a member function for streams. The <strong>exceptions( )</strong> function returns a bitmask<a l:href="#n42" type="note">[42]</a> (of type <strong>iostate</strong>, which is some compiler-dependent type convertible to <strong>int</strong>) indicating which stream states will cause exceptions. If those states have already been set, an exception is thrown immediately. Of course, if you use exceptions in connection with streams, you had better be ready to catch them, which means that you need to wrap all stream processing with a <strong>try</strong> block that has an <strong>ios::failure</strong> handler. Many programmers find this tedious and just check states manually where they expect errors to occur (since, for example, they don’t expect <strong>bad( )</strong> to return <strong>true</strong> most of the time anyway). This is another reason that having streams throw exceptions is optional and not the default. In any case, you can choose how you want to handle stream errors<sup>.</sup></p></section></section></section></section><section><title><p>File iostreams</p></title><section><p>Manipulating files with iostreams is much easier and safer than using <strong>stdio </strong>in C. All you do to open a file is create an object; the constructor does the work. You don’t have to explicitly close a file (although you can, using the <strong>close( )</strong> member function) because the destructor will close it when the object goes out of scope. To create a file that defaults to input, make an <strong>ifstream</strong> object. To create one that defaults to output, make an <strong>ofstream</strong> object. An <strong>fstream</strong> object can do both input and output<sup>.</sup></p><p>The file stream classes fit into the iostreams classes as shown in the following figure.</p><empty-line/><empty-line/><empty-line/><p><image l:href="#2"/></p><p>As before, the classes you actually use are template specializations defined by type definitions. For example, <strong>ifstream</strong>, which processes files of <strong>char</strong>, is defined as<sup>.</sup></p><p>typedef basic_ifstream&lt;char&gt; ifstream;</p><empty-line/></section><section><title><p>A File-Processing Example</p></title><p>Here’s an example that shows many of the features discussed so far. Notice the inclusion of <strong>&lt;fstream&gt; </strong>to declare the file I/O classes. Although on many platforms this will also include <strong>&lt;iostream&gt;</strong> automatically, compilers are not required to do so. If you want portable code, always include both headers<sup>.</sup></p><p>//: C04:Strfile.cpp</p><p>// Stream I/O with files</p><p>// The difference between get() &amp; getline()</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  const int sz = 100; // Buffer size;</p><p>  char buf[sz];</p><p>  {</p><p>    ifstream in("Strfile.cpp"); // Read</p><p>    assure(in, "Strfile.cpp"); // Verify open</p><p>    ofstream out("Strfile.out"); // Write</p><p>    assure(out, "Strfile.out");</p><p>    int i = 1; // Line counter</p><empty-line/><p>    // A less-convenient approach for line input:</p><p>    while(in.get(buf, sz)) { // Leaves \n in input</p><p>      in.get(); // Throw away next character (\n)</p><p>      cout &lt;&lt; buf &lt;&lt; endl; // Must add \n</p><p>      // File output just like standard I/O:</p><p>      out &lt;&lt; i++ &lt;&lt; ": " &lt;&lt; buf &lt;&lt; endl;</p><p>    }</p><p>  } // Destructors close in &amp; out</p><empty-line/><p>  ifstream in("Strfile.out");</p><p>  assure(in, "Strfile.out");</p><p>  // More convenient line input:</p><p>  while(in.getline(buf, sz)) { // Removes \n</p><p>    char* cp = buf;</p><p>    while(*cp != ':')</p><p>      cp++;</p><p>    cp += 2; // Past ": "</p><p>    cout &lt;&lt; cp &lt;&lt; endl; // Must still add \n</p><p>  }</p><p>} ///:~</p><empty-line/><p>The creation of both the <strong>ifstream</strong> and <strong>ofstream</strong> are followed by an <strong>assure( )</strong> to guarantee the file was successfully opened. Here again the object, used in a situation in which the compiler expects a Boolean result, produces a value that indicates success or failure<sup>.</sup></p><p>The first <strong>while</strong> loop demonstrates the use of two forms of the <strong>get( )</strong> function. The first gets characters into a buffer and puts a zero terminator in the buffer when either <strong>sz-1</strong> characters have been read or the third argument (defaulted to <strong>'\n'</strong>) is encountered. The <strong>get( )</strong> function leaves the terminator character in the input stream, so this terminator must be thrown away via <strong>in.get( )</strong> using the form of <strong>get( )</strong> with no argument, which fetches a single byte and returns it as an <strong>int</strong>. You can also use the <strong>ignore( )</strong> member function, which has two default arguments. The first argument is the number of characters to throw away and defaults to one. The second argument is the character at which the <strong>ignore( )</strong> function quits (after extracting it) and defaults to <strong>EOF</strong><sup><strong>.</strong></sup></p><p>Next, you see two output statements that look similar: one to <strong>cout </strong>and one to the file <strong>out</strong>. Notice the convenience here; you don’t need to worry about what kind of object you’re dealing with because the formatting statements work the same with all <strong>ostream</strong> objects. The first one echoes the line to standard output, and the second writes the line out to the new file and includes a line number<sup>.</sup></p><p>To demonstrate <strong>getline( )</strong>, open the file we just created and strip off the line numbers. To ensure the file is properly closed before opening it to read, you have two choices. You can surround the first part of the program with braces to force the <strong>out</strong> object out of scope, thus calling the destructor and closing the file, which is done here. You can also call <strong>close( )</strong> for both files; if you do this, you can even reuse the <strong>in</strong> object by calling the <strong>open( )</strong> member function<sup>.</sup></p><p>The second <strong>while</strong> loop shows how <strong>getline( )</strong> removes the terminator character (its third argument, which defaults to <strong>'\n'</strong>) from the input stream when it’s encountered. Although <strong>getline( )</strong>, like <strong>get( )</strong>, puts a zero in the buffer, it still doesn’t insert the terminating character<sup>.</sup></p><p>This example, as well as most of the examples in this chapter, assumes that each call to any overload of <strong>getline( )</strong> will actually encounter a newline character. If this is not the case, the eofbit state of the stream will be set and the call to <strong>getline( )</strong> will return <strong>false</strong>, causing the program to lose the last line of input.</p></section><section><title><p>Open modes</p></title><p>You can control the way a file is opened by overriding the constructor’s default arguments. The following table shows the flags that control the mode of the file:<sup>.</sup></p><table><tr align="left"><th align="left" valign="top">Flag</th><th align="left" valign="top">Function</th></tr><tr align="left"><td align="left" valign="top"><strong>ios::in</strong></td><td align="left" valign="top">Opens an input file. Use this as an open mode for an <strong>ofstream</strong> to prevent truncating an existing file.</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::out</strong></td><td align="left" valign="top">Opens an output file. When used for an <strong>ofstream</strong> without <strong>ios::app</strong>, <strong>ios::ate</strong> or <strong>ios::in</strong>, <strong>ios::trunc</strong> is implied.</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::app</strong></td><td align="left" valign="top">Opens an output file for appending only.</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::ate</strong></td><td align="left" valign="top">Opens an existing file (either input or output) and seeks to the end.</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::trunc</strong></td><td align="left" valign="top">Truncates the old file, if it already exists.</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::binary</strong></td><td align="left" valign="top">Opens a file in <emphasis>binary mode</emphasis>. The default is <emphasis>text mode</emphasis>.</td></tr></table><empty-line/><p>You can combine these flags using a bitwise <emphasis>or</emphasis> operation<sup>.</sup></p><p>The binary flag, while portable, only has an effect on some non-UNIX systems, such as operating systems derived from MS-DOS, that have special conventions for storing end-of-line delimiters. For example, on MS-DOS systems in text mode (which is the default), every time you output a newline character (<strong>'\n'</strong>), the file system actually outputs two characters, a carriage-return/linefeed pair (CRLF), which is the pair of ASCII characters <strong>0x0D</strong> and <strong>0x0A</strong>. Conversely, when you read such a file back into memory in text mode, each occurrence of this pair of bytes causes a <strong>'\n'</strong> to be sent to the program in its place. If you want to bypass this special processing, you open files in binary mode. Binary mode has nothing whatsoever to do with whether you <emphasis>can</emphasis> write raw bytes to a file—you <emphasis>always</emphasis> can (by calling <strong>write( )</strong>) . You should, however, open a file in binary mode when you’ll be using <strong>read( )</strong> or <strong>write( )</strong>, because these functions take a byte count parameter. Having the extra <strong>'\r'</strong> characters will throw your byte count off in those instances. You should also open a file in binary mode if you’re going to use the stream-positioning commands discussed later in this chapter<sup>.</sup></p><p>You can open a file for both input and output by declaring an <strong>fstream</strong> object. When declaring an <strong>fstream</strong> object, you must use enough of the open mode flags mentioned earlier to let the file system know whether you want to input, output, or both. To switch from output to input, you need to either flush the stream or change the file position. To change from input to output, change the file position. To create a file via an <strong>fstream</strong> object, you need to use the <strong>ios::trunc</strong> open mode flag in the constructor call if you will actually do both input and output<sup>.</sup></p></section></section><section><title><p>Iostream buffering</p></title><p>Good design practice dictates that whenever you create a new class, you should endeavor to hide the details of the underlying implementation as much possible from the user of the class. You show them only what they need to know and make the rest <strong>private </strong>to avoid confusion. When using inserters and extractors, you normally don’t know or care where the bytes are being produced or consumed, whether you’re dealing with standard I/O, files, memory, or some newly created class or device<sup>.</sup></p><p>A time comes, however, when it is important to communicate with the part of the iostream that produces and consumes bytes. To provide this part with a common interface and still hide its underlying implementation, the standard library abstracts it into its own class, called <strong>streambuf</strong>. Each iostream object contains a pointer to some kind of <strong>streambuf</strong>. (The kind depends on whether it deals with standard I/O, files, memory, and so on.) You can access the <strong>streambuf </strong>directly; for example, you can move raw bytes into and out of the <strong>streambuf</strong>, without formatting them through the enclosing iostream. This is accomplished by calling member functions for the <strong>streambuf</strong> object<sup>.</sup></p><p>Currently, the most important thing for you to know is that every iostream object contains a pointer to a <strong>streambuf</strong> object, and the <strong>streambuf</strong> object has some member functions you can call if necessary. For file and string streams, there are specialized types of stream buffers, as the following figure illustrates<sup>.</sup></p><p><image l:href="#3"/></p><p>To allow you to access the <strong>streambuf</strong>, every iostream object has a member function called <strong>rdbuf( )</strong> that returns the pointer to the object’s <strong>streambuf</strong>. This way you can call any member function for the underlying <strong>streambuf</strong>. However, one of the most interesting things you can do with the <strong>streambuf</strong> pointer is to connect it to another iostream object using the <strong>&lt;&lt;</strong> operator. This drains all the characters from your object into the one on the left side of the <strong>&lt;&lt;</strong>. If you want to move all the characters from one iostream to another, you don’t have to go through the tedium (and potential coding errors) of reading them one character or one line at a time. It’s a much more elegant approach<sup>.</sup></p><p>For example, here’s a simple program that opens a file and sends the contents to standard output (similar to the previous example):<sup>.</sup></p><p>//: C04:Stype.cpp</p><p>// Type a file to standard output</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  ifstream in("Stype.cpp");</p><p>  assure(in, "Stype.cpp");</p><p>  cout &lt;&lt; in.rdbuf(); // Outputs entire file</p><p>} ///:~</p><empty-line/><p>An <strong>ifstream</strong> is created using the source code file for this program as an argument. The <strong>assure( ) </strong>function reports a failure if the file cannot be opened. All the work really happens in the statement:<sup>.</sup></p><p>cout &lt;&lt; in.rdbuf();</p><empty-line/><p>which sends the entire contents of the file to <strong>cout</strong>. This is not only more succinct to code, it is often more efficient than moving the bytes one at a time<sup>.</sup></p><p>A form of <strong>get( )</strong> allows you to write directly into the <strong>streambuf</strong> of another object. The first argument is a reference to the destination <strong>streambuf,</strong> and the second is the terminating character (‘<strong>\n’</strong> by default), which stops the <strong>get( )</strong> function. So there is yet another way to print a file to standard output:<sup>.</sup></p><p>//: C04:Sbufget.cpp</p><p>// Copies a file to standard output</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  ifstream in("Sbufget.cpp");</p><p>  assure(in);</p><p>  streambuf&amp; sb = *cout.rdbuf();</p><p>  while (!in.get(sb).eof()) {</p><p>    if (in.fail())          // Found blank line</p><p>      in.clear();</p><p>    cout &lt;&lt; char(in.get()); // Process '\n'</p><p>  }</p><p>} ///:~</p><empty-line/><p>The <strong>rdbuf( )</strong> function returns a pointer, so it must be dereferenced to satisfy the function’s need to see an object. Stream buffers are not meant to be copied (they have no copy constructor), so we define <strong>sb</strong> as a <emphasis>reference</emphasis> to <strong>cout</strong>’s stream buffer. We need the calls to <strong>fail( )</strong> and <strong>clear( )</strong> in case the input file has a blank line (this one does). When this particular overloaded version of <strong>get( )</strong> sees two newlines in a row (evidence of a blank line), it sets the input stream’s fail bit, so we must call <strong>clear( )</strong> to reset it so that the stream can continue to be read. The second call to <strong>get( )</strong> extracts and echoes each newline delimiter. (Remember, the <strong>get( )</strong> function doesn’t extract its delimiter like <strong>getline( )</strong> does.)<sup>.</sup></p><p>You probably won’t need to use a technique like this often, but it’s nice to know it exists.<a l:href="#n43" type="note">[43]</a></p></section><section><title><p>Seeking in iostreams</p></title><p>Each type of iostream has a concept of where its "next" character will come from (if it’s an <strong>istream</strong>) or go (if it’s an <strong>ostream</strong>). In some situations, you might want to move this stream position. You can do so using two models: one uses an absolute location in the stream called the <strong>streampos</strong>; the second works like the Standard C library functions <strong>fseek( )</strong> for a file and moves a given number of bytes from the beginning, end, or current position in the file<sup>.</sup></p><p>The <strong>streampos</strong> approach requires that you first call a "tell" function: <strong>tellp( )</strong> for an <strong>ostream</strong> or <strong>tellg( )</strong> for an <strong>istream</strong>. (The "p" refers to the "put pointer," and the "g" refers to the "get pointer.") This function returns a <strong>streampos</strong> you can later use in calls to <strong>seekp( )</strong> for an <strong>ostream</strong> or <strong>seekg( )</strong> for an <strong>istream</strong>, when you want to return to that position in the stream<sup>.</sup></p><p>The second approach is a relative seek and uses overloaded versions of <strong>seekp( )</strong> and <strong>seekg( )</strong>. The first argument is the number of characters to move: it can be positive or negative. The second argument is the seek direction:<sup>.</sup></p><table><tr align="left"><td align="left" valign="top"><strong>ios::beg</strong></td><td align="left" valign="top">From beginning of stream</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::cur</strong></td><td align="left" valign="top">Current position in stream</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::end</strong></td><td align="left" valign="top">From end of stream</td></tr></table><empty-line/><p>Here’s an example that shows the movement through a file, but remember, you’re not limited to seeking within files, as you are with C and <strong>cstdio</strong>. With C++, you can seek in any type of iostream (although the standard stream objects, such as <strong>cin</strong> and <strong>cout</strong>, explicitly disallow it):<sup>.</sup></p><p>//: C04:Seeking.cpp</p><p>// Seeking in iostreams</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;cstring&gt;</p><p>#include &lt;fstream&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  const int STR_NUM = 5, STR_LEN = 30;</p><p>  char origData[STR_NUM][STR_LEN] = {</p><p>    "Hickory dickory dus. . .",</p><p>    "Are you tired of C++?",</p><p>    "Well, if you have,",</p><p>    "That's just too bad,",</p><p>    "There's plenty more for us!"</p><p>  };</p><p>  char readData[STR_NUM][STR_LEN] = { 0 };</p><p>  ofstream out("Poem.bin", ios::out | ios::binary);</p><p>  assure(out, "Poem.bin");</p><p>  for(size_t i = 0; i &lt; STR_NUM; i++)</p><p>    out.write(origData[i], STR_LEN);</p><p>  out.close();</p><p>  ifstream in("Poem.bin", ios::in | ios::binary);</p><p>  assure(in, "Poem.bin");</p><p>  in.read(readData[0], STR_LEN);</p><p>  assert(strcmp(readData[0], "Hickory dickory dus. . .")</p><p>    == 0);</p><p>  // Seek -STR_LEN bytes from the end of file</p><p>  in.seekg(-STR_LEN, ios::end);</p><p>  in.read(readData[1], STR_LEN);</p><p>  assert(strcmp(readData[1], "There's plenty more for us!")</p><p>    == 0);</p><p>  // Absolute seek (like using operator[] with a file)</p><p>  in.seekg(3 * STR_LEN);</p><p>  in.read(readData[2], STR_LEN);</p><p>  assert(strcmp(readData[2], "That's just too bad,") == 0);</p><p>  // Seek backwards from current position</p><p>  in.seekg(-STR_LEN * 2, ios::cur);</p><p>  in.read(readData[3], STR_LEN);</p><p>  assert(strcmp(readData[3], "Well, if you have,") == 0);</p><p>  // Seek from the begining of the file</p><p>  in.seekg(1 * STR_LEN, ios::beg);</p><p>  in.read(readData[4], STR_LEN);</p><p>  assert(strcmp(readData[4], "Are you tired of C++?")</p><p>    == 0);</p><p>} ///:~</p><empty-line/><p>This program writes a (very clever?) poem to a file using a binary output stream. Since we reopen it as an <strong>ifstream</strong>, we use <strong>seekg( )</strong> to position the "get pointer." As you can see, you can seek from the beginning or end of the file or from the current file position. Obviously, you must provide a positive number to move from the beginning of the file and a negative number to move back from the end<sup>.</sup></p><p>Now that you know about the <strong>streambuf</strong> and how to seek, you can understand an alternative method (besides using an <strong>fstream</strong> object) for creating a stream object that will both read and write a file. The following code first creates an <strong>ifstream</strong> with flags that say it’s both an input and an output file. You can’t write to an <strong>ifstream</strong>, of course, so you need to create an <strong>ostream</strong> with the underlying stream buffer:<sup>.</sup></p><p>ifstream in("filename", ios::in | ios::out);</p><p>ostream out(in.rdbuf());</p><empty-line/><p>You might wonder what happens when you write to one of these objects. Here’s an example:<sup>.</sup></p><p>//: C04:Iofile.cpp</p><p>// Reading &amp; writing one file</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  ifstream in("Iofile.cpp");</p><p>  assure(in, "Iofile.cpp");</p><p>  ofstream out("Iofile.out");</p><p>  assure(out, "Iofile.out");</p><p>  out &lt;&lt; in.rdbuf(); // Copy file</p><p>  in.close();</p><p>  out.close();</p><p>  // Open for reading and writing:</p><p>  ifstream in2("Iofile.out", ios::in | ios::out);</p><p>  assure(in2, "Iofile.out");</p><p>  ostream out2(in2.rdbuf());</p><p>  cout &lt;&lt; in2.rdbuf();  // Print whole file</p><p>  out2 &lt;&lt; "Where does this end up?";</p><p>  out2.seekp(0, ios::beg);</p><p>  out2 &lt;&lt; "And what about this?";</p><p>  in2.seekg(0, ios::beg);</p><p>  cout &lt;&lt; in2.rdbuf();</p><p>} ///:~</p><empty-line/><p>The first five lines copy the source code for this program into a file called <strong>iofile.out</strong> and then close the files. This gives us a safe text file to play with. Then the aforementioned technique is used to create two objects that read and write to the same file. In <strong>cout &lt;&lt; in2.rdbuf( )</strong>, you can see the "get" pointer is initialized to the beginning of the file. The "put" pointer, however, is set to the end of the file because "Where does this end up?" appears appended to the file. However, if the put pointer is moved to the beginning with a <strong>seekp( )</strong>, all the inserted text <emphasis>overwrites </emphasis>the existing text. Both writes are seen when the get pointer is moved back to the beginning with a <strong>seekg( )</strong>, and the file is displayed. Of course, the file is automatically saved and closed when <strong>out2</strong> goes out of scope and its destructor is called<sup>.</sup></p></section><section><title><p>String iostreams</p></title><section><p>A string stream works directly with memory instead of a file or standard output. It allows you to use the same reading and formatting functions that you use with <strong>cin</strong> and <strong>cout</strong> to manipulate bytes in memory. On old computers, the memory was referred to as <emphasis>core,</emphasis> so this type of functionality is often called <emphasis>in-core formatting</emphasis><sup><emphasis>.</emphasis></sup></p><p>The class names for string streams echo those for file streams. If you want to create a string stream to extract characters from, you create an <strong>istringstream</strong>. If you want to put characters into a string stream, you create an <strong>ostringstream</strong>. All declarations for string stream are in the standard header <strong>&lt;sstream&gt;</strong>. As usual, there are class templates that fit into the iostreams hierarchy, as shown in the following figure:<sup>.</sup></p><p><image l:href="#4"/></p></section><section><title><p>Input string streams</p></title><p>To read from a string using stream operations, you create an <strong>istringstream</strong> object initialized with the string. The following program shows how to use an <strong>istringstream</strong> object.</p><p>//: C04:Istring.cpp</p><p>// Input string streams</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cmath&gt;  // For fabs()</p><p>#include &lt;iostream&gt;</p><p>#include &lt;limits&gt; // For epsilon()</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  istringstream s("47 1.414 This is a test");</p><p>  int i;</p><p>  double f;</p><p>  s &gt;&gt; i &gt;&gt; f; // Whitespace-delimited input</p><p>  assert(i == 47);</p><p>  double relerr = (fabs(f) - 1.414) / 1.414;</p><p>  assert(relerr &lt;= numeric_limits&lt;double&gt;::epsilon());</p><p>  string buf2;</p><p>  s &gt;&gt; buf2;</p><p>  assert(buf2 == "This");</p><p>  cout &lt;&lt; s.rdbuf(); // " is a test"</p><p>} ///:~</p><empty-line/><p>You can see that this is a more flexible and general approach to transforming character strings to typed values than the standard C library functions such as <strong>atof( )</strong>, <strong>atoi( )</strong>, even though the latter may be more efficient for single conversions<sup>.</sup></p><p>In the expression <strong>s &gt;&gt; i &gt;&gt; f</strong>, the first number is extracted into <strong>i,</strong> and the second into <strong>f</strong>. This isn’t "the first whitespace-delimited set of characters" because it depends on the data type it’s being extracted into. For example, if the string were instead, "<strong>1.414 47 This is a test</strong>," then <strong>i</strong> would get the value 1 because the input routine would stop at the decimal point. Then <strong>f</strong> would get <strong>0.414</strong>. This could be useful if you want to break a floating-point number into a whole number and a fraction part. Otherwise it would seem to be an error. The second <strong>assert( )</strong> calculates the relative error between what we read and what we expected; it’s always better to do this than to compare floating-point numbers for equality. The constant returned by <strong>epsilon( )</strong>, defined in <strong>&lt;limits&gt;</strong>, represents the <emphasis>machine epsilon</emphasis> for double-precision numbers, which is the best tolerance you can expect comparisons of <strong>double</strong>s to satisfy.<a l:href="#n44" type="note">[44]</a></p><p>As you may already have guessed, <strong>buf2</strong> doesn’t get the rest of the string, just the next white-space-delimited word. In general, it’s best to use the extractor in iostreams when you know the exact sequence of data in the input stream and you’re converting to some type other than a character string. However, if you want to extract the rest of the string all at once and send it to another iostream, you can use <strong>rdbuf( )</strong> as shown<sup>.</sup></p><p>To test the <strong>Date</strong> extractor at the beginning of this chapter, we used an input string stream with the following test program:</p><p>//: C04:DateIOTest.cpp</p><p>//{L} ../C02/Date</p><p>#include &lt;iostream&gt;</p><p>#include &lt;sstream&gt;</p><p>#include "../C02/Date.h"</p><p>using namespace std;</p><empty-line/><p>void testDate(const string&amp; s) {</p><p>  istringstream os(s);</p><p>  Date d;</p><p>  os &gt;&gt; d;</p><p>  if (os)</p><p>    cout &lt;&lt; d &lt;&lt; endl;</p><p>  else</p><p>    cout &lt;&lt; "input error with \"" &lt;&lt; s &lt;&lt; "\"\n";</p><p>}</p><empty-line/><p>int main() {</p><p>  testDate("08-10-2003");</p><p>  testDate("8-10-2003");</p><p>  testDate("08 - 10 - 2003");</p><p>  testDate("A-10-2003");</p><p>  testDate("08%10/2003");</p><p>} ///:~</p><empty-line/><p>Each string literal in <strong>main( )</strong> is passed by reference to <strong>testDate( )</strong>, which in turn wraps it in an <strong>istringstream</strong> so we can test the stream extractor we wrote for <strong>Date</strong> objects. The function <strong>testDate( )</strong> also begins to test the inserter, <strong>operator&lt;&lt;( )</strong><sup><strong>.</strong></sup></p></section><section><title><p>Output string streams</p></title><p>To create an output string stream to put data into, you just create an <strong>ostringstream</strong> object, which manages a dynamically sized character buffer to hold whatever you insert. To get the formatted result as a <strong>string</strong> object, you call the <strong>str( )</strong> member function. Here’s an example:<sup>.</sup></p><p>//: C04:Ostring.cpp</p><p>// Illustrates ostringstream</p><p>#include &lt;iostream&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  cout &lt;&lt; "type an int, a float and a string: ";</p><p>  int i;</p><p>  float f;</p><p>  cin &gt;&gt; i &gt;&gt; f;</p><p>  cin &gt;&gt; ws; // Throw away white space</p><p>  string stuff;</p><p>  getline(cin, stuff); // Get rest of the line</p><p>  ostringstream os;</p><p>  os &lt;&lt; "integer = " &lt;&lt; i &lt;&lt; endl;</p><p>  os &lt;&lt; "float = " &lt;&lt; f &lt;&lt; endl;</p><p>  os &lt;&lt; "string = " &lt;&lt; stuff &lt;&lt; endl;</p><p>  string result = os.str();</p><p>  cout &lt;&lt; result &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>This is similar to the <strong>Istring.cpp</strong> example earlier that fetched an <strong>int</strong> and a <strong>float</strong>. A sample execution follows (the keyboard input is in bold type)<sup>.</sup></p><p>type an int, a float and a string: <strong>10 20.5 the end</strong></p><p>integer = 10</p><p>float = 20.5</p><p>string = the end</p><empty-line/><p>You can see that, like the other output streams, you can use the ordinary formatting tools, such as the <strong>&lt;&lt;</strong> operator and <strong>endl</strong>, to send bytes to the <strong>ostringstream</strong>. The <strong>str( )</strong> function returns a new <strong>string</strong> object every time you call it so the underlying <strong>stringbuf</strong> object owned by the string stream is left undisturbed<sup>.</sup></p><p>In the previous chapter, we presented a program, <strong>HTMLStripper.cpp</strong>, that removed all HTML tags and special codes from a text file. As promised, here is a more elegant version using string streams.</p><p>//: C04:HTMLStripper2.cpp</p><p>//{L} ../C03/ReplaceAll</p><p>// Filter to remove html tags and markers</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;stdexcept&gt;</p><p>#include &lt;string&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>string&amp; replaceAll(string&amp; context, const string&amp; from,</p><p>  const string&amp; to);</p><empty-line/><p>string&amp; stripHTMLTags(string&amp; s) throw(runtime_error) {</p><p>  size_t leftPos;</p><p>  while ((leftPos = s.find('&lt;')) != string::npos) {</p><p>    size_t rightPos = s.find('&gt;', leftPos+1);</p><p>    if (rightPos == string::npos) {</p><p>      ostringstream msg;</p><p>      msg &lt;&lt; "Incomplete HTML tag starting in position "</p><p>          &lt;&lt; leftPos;</p><p>      throw runtime_error(msg.str());</p><p>    }</p><p>    s.erase(leftPos, rightPos - leftPos + 1);</p><p>  }</p><p>  // Remove all special HTML characters</p><p>  replaceAll(s, "&lt;", "&lt;");</p><p>  replaceAll(s, "&gt;", "&gt;");</p><p>  replaceAll(s, "&amp;&amp;", "&amp;");</p><p>  replaceAll(s, "&amp;nbsp;", " ");</p><p>  // Etc...</p><p>  return s;</p><p>}</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  requireArgs(argc, 1,</p><p>    "usage: HTMLStripper2 InputFile");</p><p>  ifstream in(argv[1]);</p><p>  assure(in, argv[1]);</p><p>  // Read entire file into string; then strip</p><p>  ostringstream ss;</p><p>  ss &lt;&lt; in.rdbuf();</p><p>  try {</p><p>    string s = ss.str();</p><p>    cout &lt;&lt; stripHTMLTags(s) &lt;&lt; endl;</p><p>    return EXIT_SUCCESS;</p><p>  }</p><p>  catch (runtime_error&amp; x) {</p><p>    cout &lt;&lt; x.what() &lt;&lt; endl;</p><p>    return EXIT_FAILURE;</p><p>  }</p><p>} ///:~</p><empty-line/><p>In this program we read the entire file into a string by inserting a <strong>rdbuf( )</strong> call to the file stream into an <strong>ostringstream</strong>. Now it’s an easy matter to search for HTML delimiter pairs and erase them without having to worry about crossing line boundaries like we had to with the previous version in Chapter 3<sup>.</sup></p><p>The following example shows how to use a bidirectional (that is, read/write) string stream.</p><p>//: C04:StringSeeking.cpp</p><p>// Reads and writes a string stream</p><p>//{-bor}</p><p>#include &lt;cassert&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  string text = "We will sell no wine";</p><p>  stringstream ss(text);</p><p>  ss.seekp(0, ios::end);</p><p>  ss &lt;&lt; " before its time.";</p><p>  assert(ss.str() ==</p><p>    "We will sell no wine before its time.");</p><p>  // Change "sell" to "ship"</p><p>  ss.seekg(9, ios::beg);</p><p>  string word;</p><p>  ss &gt;&gt; word;</p><p>  assert(word == "ell");</p><p>  ss.seekp(9, ios::beg);</p><p>  ss &lt;&lt; "hip";</p><p>  // Change "wine" to "code"</p><p>  ss.seekg(16, ios::beg);</p><p>  ss &gt;&gt; word;</p><p>  assert(word == "wine");</p><p>  ss.seekp(16, ios::beg);</p><p>  ss &lt;&lt; "code";</p><p>  assert(ss.str() ==</p><p>    "We will ship no code before its time.");</p><p>  ss.str("A horse of a different color.");</p><p>  assert(ss.str() == "A horse of a different color.");</p><p>} ///:~</p><empty-line/><p>As always, to move the put pointer, you call <strong>seekp( )</strong>, and to reposition the get pointer, you call <strong>seekg( )</strong>. Even though we didn’t show it with this example, string streams are a little more forgiving than file streams in that you can switch from reading to writing or vice-versa at any time. You don’t need to reposition the get or put pointers or flush the stream. This program also illustrates the overload of <strong>str( )</strong> that replaces the stream’s underlying <strong>stringbuf</strong> with a new string<sup>.</sup></p></section></section><section><title><p>Output stream formatting</p></title><section><p>The goal of the iostreams design is to allow you to easily move and/or format characters. It certainly wouldn’t be useful if you couldn’t do most of the formatting provided by C’s <strong>printf( )</strong> family of functions. In this section, you’ll learn all the output formatting functions that are available for iostreams, so you can format your bytes the way you want them<sup>.</sup></p><p>The formatting functions in iostreams can be somewhat confusing at first because there’s often more than one way to control the formatting: through both member functions and manipulators. To further confuse things, a generic member function sets state flags to control formatting, such as left or right justification, to use uppercase letters for hex notation, to always use a decimal point for floating-point values, and so on. On the other hand, separate member functions set and read values for the fill character, the field width, and the precision<sup>.</sup></p><p>In an attempt to clarify all this, we’ll first examine the internal formatting data of an iostream , along with the member functions that can modify that data. (Everything can be controlled through the member functions, if desired.) We’ll cover the manipulators separately<sup>.</sup></p></section><section><title><p>Format flags</p></title><p>The class <strong>ios</strong> contains data members to store all the formatting information pertaining to a stream. Some of this data has a range of values and is stored in variables: the floating-point precision, the output field width, and the character used to pad the output (normally a space). The rest of the formatting is determined by flags, which are usually combined to save space and are referred to collectively as the <emphasis>format flags</emphasis>. You can find out the value of the format flags with the <strong>ios::flags( )</strong> member function, which takes no arguments and returns an object of type <strong>fmtflags</strong> (usually a synonym for <strong>long</strong>) that contains the current format flags. All the rest of the functions make changes to the format flags and return the previous value of the format flags<sup>.</sup></p><p>fmtflags ios::flags(fmtflags newflags);</p><p>fmtflags ios::setf(fmtflags ored_flag);</p><p>fmtflags ios::unsetf(fmtflags clear_flag);</p><p>fmtflags ios::setf(fmtflags bits, fmtflags field);</p><empty-line/><p>The first function forces <emphasis>all</emphasis> the flags to change, which you do sometimes. More often, you change one flag at a time using the remaining three functions<sup>.</sup></p><p>The use of <strong>setf( )</strong> can seem somewhat confusing. To know which overloaded version to use, you must know what type of flag you’re changing. There are two types of flags: those that are simply on or off, and those that work in a group with other flags. The on/off flags are the simplest to understand because you turn them on with <strong>setf(fmtflags)</strong> and off with <strong>unsetf(fmtflags)</strong>. These flags are shown in the following table<sup>.</sup></p><table><tr align="left"><th align="left" valign="top">on/off flag</th><th align="left" valign="top">Effect</th></tr><tr align="left"><td align="left" valign="top"><strong>ios::skipws</strong></td><td align="left" valign="top">Skip white space. (For input; this is the default.)</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::showbase</strong></td><td align="left" valign="top">Indicate the numeric base (as set, for example, by <strong>dec</strong>, <strong>oct</strong>, or <strong>hex</strong>) when printing an integral value. Input streams also recognize the base prefix when <strong>showbase</strong> is on.</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::showpoint</strong></td><td align="left" valign="top">Show decimal point and trailing zeros for floating-point values.</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::uppercase</strong></td><td align="left" valign="top">Display uppercase A-F for hexadecimal values and E for scientific values.</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::showpos</strong></td><td align="left" valign="top">Show plus sign (+) for positive values.</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::unitbuf</strong></td><td align="left" valign="top">"Unit buffering." The stream is flushed after each insertion.</td></tr></table><empty-line/><p>For example, to show the plus sign for <strong>cout</strong>, you say <strong>cout.setf(ios::showpos)</strong>. To stop showing the plus sign, you say <strong>cout.unsetf(ios::showpos)</strong><sup><strong>.</strong></sup></p><p>The <strong>unitbuf</strong> flag controls <emphasis>unit buffering</emphasis>, which means that each insertion is flushed to its output stream immediately. This is handy for error tracing, so that in case of a program crash, your data is still written to the log file. The following program illustrates unit buffering.</p><p>//: C04:Unitbuf.cpp</p><p>#include &lt;cstdlib&gt;  // For abort()</p><p>#include &lt;fstream&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  ofstream out("log.txt");</p><p>  out.setf(ios::unitbuf);</p><p>  out &lt;&lt; "one\n";</p><p>  out &lt;&lt; "two\n";</p><p>  abort();</p><p>} ///:~</p><empty-line/><p>It is necessary to turn on unit buffering before any insertions are made to the stream. When we commented out the call to <strong>setf( )</strong>, one particular compiler had written only the letter ‘o’ to the file <strong>log.txt</strong>. With unit buffering, no data was lost<sup>.</sup></p><p>The standard error output stream <strong>cerr</strong> has unit buffering turned on by default. There is a cost for unit buffering, of course, so if an output stream is heavily used, don’t enable unit buffering unless efficiency is not a consideration<sup>.</sup></p></section><section><title><p>Format fields</p></title><p>The second type of formatting flags work in a group. Only one of these flags can be, like the buttons on old car radios—you push one in, the rest pop out. Unfortunately this doesn’t happen automatically, and you have to pay attention to what flags you’re setting so that you don’t accidentally call the wrong <strong>setf( )</strong> function. For example, there’s a flag for each of the number bases: hexadecimal, decimal, and octal. Collectively, these flags are referred to as the <strong>ios::basefield</strong>. If the <strong>ios::dec</strong> flag is set and you call <strong>setf(ios::hex)</strong>, you’ll set the <strong>ios::hex</strong> flag, but you <emphasis>won’t</emphasis> clear the <strong>ios::dec</strong> bit, resulting in undefined behavior. The proper thing to do is call the second form of <strong>setf( )</strong> like this: <strong>setf(ios::hex, ios::basefield)</strong>. This function first clears all the bits in the <strong>ios::basefield</strong> and <emphasis>then</emphasis> sets <strong>ios::hex</strong>. Thus, this form of <strong>setf( )</strong> ensures that the other flags in the group "pop out" whenever you set one. Of course, the <strong>ios::hex</strong> manipulator does all this for you, automatically, so you don’t have to concern yourself with the internal details of the implementation of this class or to even <emphasis>care</emphasis> that it’s a set of binary flags. Later you’ll see that there are manipulators to provide equivalent functionality in all the places you would use <strong>setf( )</strong><sup><strong>.</strong></sup></p><p>Here are the flag groups and their effects:</p><table><tr align="left"><th align="left" valign="top">ios::basefield</th><th align="left" valign="top">effect</th></tr><tr align="left"><td align="left" valign="top"><strong>ios::dec</strong></td><td align="left" valign="top">Format integral values in base 10 (decimal) (the default radix—no prefix is visible).</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::hex</strong></td><td align="left" valign="top">Format integral values in base 16 (hexadecimal).</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::oct</strong></td><td align="left" valign="top">Format integral values in base 8 (octal).</td></tr></table><empty-line/><table><tr align="left"><th align="left" valign="top">ios::floatfield</th><th align="left" valign="top">effect</th></tr><tr align="left"><td align="left" valign="top"><strong>ios::scientific</strong></td><td align="left" valign="top">Display floating-point numbers in scientific format. Precision field indicates number of digits after the decimal point.</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::fixed</strong></td><td align="left" valign="top">Display floating-point numbers in fixed format. Precision field indicates number of digits after the decimal point.</td></tr><tr align="left"><td align="left" valign="top">"automatic" (Neither bit is set.)</td><td align="left" valign="top">Precision field indicates the total number of significant digits.</td></tr></table><empty-line/><table><tr align="left"><th align="left" valign="top">ios::adjustfield</th><th align="left" valign="top">Effect</th></tr><tr align="left"><td align="left" valign="top"><strong>ios::left</strong></td><td align="left" valign="top">Left-align values; pad on the right with the fill character.</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::right</strong></td><td align="left" valign="top">Right-align values. Pad on the left with the fill character. This is the default alignment.</td></tr><tr align="left"><td align="left" valign="top"><strong>ios::internal</strong></td><td align="left" valign="top">Add fill characters after any leading sign or base indicator, but before the value. (In other words, the sign, if printed, is left-justified while the number is right-justified).</td></tr></table></section><section><title><p>Width, fill, and precision</p></title><p>The internal variables that control the width of the output field, the fill character used to pad an output field, and the precision for printing floating-point numbers are read and written by member functions of the same name<sup>.</sup></p><table><tr align="left"><th align="left" valign="top">Function</th><th align="left" valign="top">effect</th></tr><tr align="left"><td align="left" valign="top"><strong>int ios::width( )</strong></td><td align="left" valign="top">Returns the current width. (Default is 0.) Used for both insertion and extraction.</td></tr><tr align="left"><td align="left" valign="top"><strong>int ios::width(int n)</strong></td><td align="left" valign="top">Sets the width, returns the previous width.</td></tr><tr align="left"><td align="left" valign="top"><strong>int ios::fill( )</strong></td><td align="left" valign="top">Returns the current fill character. (Default is space.)</td></tr><tr align="left"><td align="left" valign="top"><strong>int ios::fill(int n)</strong></td><td align="left" valign="top">Sets the fill character, returns the previous fill character.</td></tr><tr align="left"><td align="left" valign="top"><strong>int ios::precision( )</strong></td><td align="left" valign="top">Returns current floating-point precision. (Default is 6.) </td></tr><tr align="left"><td align="left" valign="top"><strong>int ios::precision(int n)</strong></td><td align="left" valign="top">Sets floating-point precision, returns previous precision. See <strong>ios::floatfield</strong> table for the meaning of "precision."</td></tr></table><p>The <strong>fill</strong> and <strong>precision</strong> values are fairly straightforward, but <strong>width</strong> requires some explanation. When the width is zero, inserting a value produces the minimum number of characters necessary to represent that value. A positive width means that inserting a value will produce at least as many characters as the width; if the value has fewer than width characters, the fill character is used to pad the field. However, the value will never be truncated, so if you try to print 123 with a width of two, you’ll still get 123. The field width specifies a <emphasis>minimum</emphasis> number of characters; there’s no way to specify a maximum number<sup>.</sup></p><p>The width is also distinctly different because it’s reset to zero by each inserter or extractor that could be influenced by its value. It’s really not a state variable, but rather an implicit argument to the inserters and extractors. If you want a constant width, call <strong>width( )</strong> after each insertion or extraction<sup>.</sup></p></section><section><title><p>An exhaustive example</p></title><p>To make sure you know how to call all the functions previously discussed, here’s an example that calls them all:<sup>.</sup></p><p>//: C04:Format.cpp</p><p>// Formatting Functions</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><p>#define D(A) T &lt;&lt; #A &lt;&lt; endl; A</p><empty-line/><p>int main() {</p><p>  ofstream T("format.out");</p><p>  assure(T);</p><p>  D(int i = 47;)</p><p>  D(float f = 2300114.414159;)</p><p>  const char* s = "Is there any more?";</p><empty-line/><p>  D(T.setf(ios::unitbuf);)</p><p>  D(T.setf(ios::showbase);)</p><p>  D(T.setf(ios::uppercase | ios::showpos);)</p><p>  D(T &lt;&lt; i &lt;&lt; endl;) // Default is dec</p><p>  D(T.setf(ios::hex, ios::basefield);)</p><p>  D(T &lt;&lt; i &lt;&lt; endl;)</p><p>  D(T.setf(ios::oct, ios::basefield);)</p><p>  D(T &lt;&lt; i &lt;&lt; endl;)</p><p>  D(T.unsetf(ios::showbase);)</p><p>  D(T.setf(ios::dec, ios::basefield);)</p><p>  D(T.setf(ios::left, ios::adjustfield);)</p><p>  D(T.fill('0');)</p><p>  D(T &lt;&lt; "fill char: " &lt;&lt; T.fill() &lt;&lt; endl;)</p><p>  D(T.width(10);)</p><p>  T &lt;&lt; i &lt;&lt; endl;</p><p>  D(T.setf(ios::right, ios::adjustfield);)</p><p>  D(T.width(10);)</p><p>  T &lt;&lt; i &lt;&lt; endl;</p><p>  D(T.setf(ios::internal, ios::adjustfield);)</p><p>  D(T.width(10);)</p><p>  T &lt;&lt; i &lt;&lt; endl;</p><p>  D(T &lt;&lt; i &lt;&lt; endl;) // Without width(10)</p><empty-line/><p>  D(T.unsetf(ios::showpos);)</p><p>  D(T.setf(ios::showpoint);)</p><p>  D(T &lt;&lt; "prec = " &lt;&lt; T.precision() &lt;&lt; endl;)</p><p>  D(T.setf(ios::scientific, ios::floatfield);)</p><p>  D(T &lt;&lt; endl &lt;&lt; f &lt;&lt; endl;)</p><p>  D(T.unsetf(ios::uppercase);)</p><p>  D(T &lt;&lt; endl &lt;&lt; f &lt;&lt; endl;)</p><p>  D(T.setf(ios::fixed, ios::floatfield);)</p><p>  D(T &lt;&lt; f &lt;&lt; endl;)</p><p>  D(T.precision(20);)</p><p>  D(T &lt;&lt; "prec = " &lt;&lt; T.precision() &lt;&lt; endl;)</p><p>  D(T &lt;&lt; endl &lt;&lt; f &lt;&lt; endl;)</p><p>  D(T.setf(ios::scientific, ios::floatfield);)</p><p>  D(T &lt;&lt; endl &lt;&lt; f &lt;&lt; endl;)</p><p>  D(T.setf(ios::fixed, ios::floatfield);)</p><p>  D(T &lt;&lt; f &lt;&lt; endl;)</p><empty-line/><p>  D(T.width(10);)</p><p>  T &lt;&lt; s &lt;&lt; endl;</p><p>  D(T.width(40);)</p><p>  T &lt;&lt; s &lt;&lt; endl;</p><p>  D(T.setf(ios::left, ios::adjustfield);)</p><p>  D(T.width(40);)</p><p>  T &lt;&lt; s &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>This example uses a trick to create a trace file so that you can monitor what’s happening. The macro <strong>D(a)</strong> uses the preprocessor "stringizing" to turn <strong>a</strong> into a string to display. Then it reiterates <strong>a</strong> so the statement is executed. The macro sends all the information to a file called <strong>T</strong>, which is the trace file. The output is:<sup>.</sup></p><p>int i = 47;</p><p>float f = 2300114.414159;</p><p>T.setf(ios::unitbuf);</p><p>T.setf(ios::showbase);</p><p>T.setf(ios::uppercase | ios::showpos);</p><p>T &lt;&lt; i &lt;&lt; endl;</p><p>+47</p><p>T.setf(ios::hex, ios::basefield);</p><p>T &lt;&lt; i &lt;&lt; endl;</p><p>0X2F</p><p>T.setf(ios::oct, ios::basefield);</p><p>T &lt;&lt; i &lt;&lt; endl;</p><p>057</p><p>T.unsetf(ios::showbase);</p><p>T.setf(ios::dec, ios::basefield);</p><p>T.setf(ios::left, ios::adjustfield);</p><p>T.fill('0');</p><p>T &lt;&lt; "fill char: " &lt;&lt; T.fill() &lt;&lt; endl;</p><p>fill char: 0</p><p>T.width(10);</p><p>+470000000</p><p>T.setf(ios::right, ios::adjustfield);</p><p>T.width(10);</p><p>0000000+47</p><p>T.setf(ios::internal, ios::adjustfield);</p><p>T.width(10);</p><p>+000000047</p><p>T &lt;&lt; i &lt;&lt; endl;</p><p>+47</p><p>T.unsetf(ios::showpos);</p><p>T.setf(ios::showpoint);</p><p>T &lt;&lt; "prec = " &lt;&lt; T.precision() &lt;&lt; endl;</p><p>prec = 6</p><p>T.setf(ios::scientific, ios::floatfield);</p><p>T &lt;&lt; endl &lt;&lt; f &lt;&lt; endl;</p><empty-line/><p>2.300114E+06</p><p>T.unsetf(ios::uppercase);</p><p>T &lt;&lt; endl &lt;&lt; f &lt;&lt; endl;</p><empty-line/><p>2.300114e+06</p><p>T.setf(ios::fixed, ios::floatfield);</p><p>T &lt;&lt; f &lt;&lt; endl;</p><p>2300114.500000</p><p>T.precision(20);</p><p>T &lt;&lt; "prec = " &lt;&lt; T.precision() &lt;&lt; endl;</p><p>prec = 20</p><p>T &lt;&lt; endl &lt;&lt; f &lt;&lt; endl;</p><empty-line/><p>2300114.50000000000000000000</p><p>T.setf(ios::scientific, ios::floatfield);</p><p>T &lt;&lt; endl &lt;&lt; f &lt;&lt; endl;</p><empty-line/><p>2.30011450000000000000e+06</p><p>T.setf(ios::fixed, ios::floatfield);</p><p>T &lt;&lt; f &lt;&lt; endl;</p><p>2300114.50000000000000000000</p><p>T.width(10);</p><p>Is there any more?</p><p>T.width(40);</p><p>0000000000000000000000Is there any more?</p><p>T.setf(ios::left, ios::adjustfield);</p><p>T.width(40);</p><p>Is there any more?0000000000000000000000</p><empty-line/><p>Studying this output should clarify your understanding of the iostream formatting member functions<sup>.</sup></p></section></section><section><title><p>Manipulators</p></title><section><p>As you can see from the previous program, calling the member functions for stream formatting operations can get a bit tedious. To make things easier to read and write, a set of <emphasis>manipulators</emphasis> is supplied to duplicate the actions provided by the member functions. Manipulators are a convenience because you can insert them for their effect within a containing expression; you don’t have to create a separate function-call statement<sup>.</sup></p><p>Manipulators change the state of the stream instead of (or in addition to) processing data. When you insert <strong>endl</strong> in an output expression, for example, it not only inserts a newline character, but it also <emphasis>flushes</emphasis> the stream (that is, puts out all pending characters that have been stored in the internal stream buffer but not yet output). You can also just flush a stream like this:<sup>.</sup></p><p>cout &lt;&lt; flush;</p><empty-line/><p>which causes a call to the <strong>flush( )</strong> member function, as in</p><p>cout.flush();</p><empty-line/><p>as a side effect (nothing is inserted into the stream). Additional basic manipulators will change the number base to <strong>oct</strong> (octal), <strong>dec</strong> (decimal) or <strong>hex</strong> (hexadecimal):<sup>.</sup></p><p> cout &lt;&lt; hex &lt;&lt; "0x" &lt;&lt; i &lt;&lt; endl;</p><empty-line/><p>In this case, numeric output will continue in hexadecimal mode until you change it by inserting either <strong>dec</strong> or <strong>oct</strong> in the output stream.</p><p>There’s also a manipulator for extraction that "eats" white space:<sup>.</sup></p><p>cin &gt;&gt; ws;</p><empty-line/><p>Manipulators with no arguments are provided in <strong>&lt;iostream&gt;</strong>. These include <strong>dec</strong>, <strong>oct</strong>, and <strong>hex</strong> , which perform the same action as, respectively, <strong>setf(ios::dec, ios::basefield)</strong>, <strong>setf(ios::oct, ios::basefield)</strong>, and <strong>setf(ios::hex, ios::basefield)</strong>, albeit more succinctly. The <strong>&lt;iostream&gt;</strong> header also includes <strong>ws</strong>, <strong>endl</strong>, and <strong>flush</strong> and the additional set shown here:<sup>.</sup></p><table><tr align="left"><th align="left" valign="top">Manipulator</th><th align="left" valign="top">Effect</th></tr><tr align="left"><td align="left" valign="top"><strong>showbase noshowbase</strong></td><td align="left" valign="top">Indicate the numeric base (<strong>dec</strong>, <strong>oct</strong>, or <strong>hex</strong>) when printing an integral value. The format used can be read by the C++ compiler.</td></tr><tr align="left"><td align="left" valign="top"/><td align="left" valign="top"/></tr><tr align="left"><td align="left" valign="top"><strong>showpos noshowpos</strong></td><td align="left" valign="top">Show plus sign (+) for positive values.</td></tr><tr align="left"><td align="left" valign="top"/><td align="left" valign="top"/></tr><tr align="left"><td align="left" valign="top"><strong>uppercase nouppercase</strong></td><td align="left" valign="top">Display uppercase A-F for hexadecimal values, and display E for scientific values.</td></tr><tr align="left"><td align="left" valign="top"/><td align="left" valign="top"/></tr><tr align="left"><td align="left" valign="top"><strong>showpoint noshowpoint</strong></td><td align="left" valign="top">Show decimal point and trailing zeros for floating-point values.</td></tr><tr align="left"><td align="left" valign="top"/><td align="left" valign="top"/></tr><tr align="left"><td align="left" valign="top"><strong>skipws noskipws</strong></td><td align="left" valign="top">Skip white space on input.</td></tr><tr align="left"><td align="left" valign="top"/><td align="left" valign="top"/></tr><tr align="left"><td align="left" valign="top"><strong>left right internal</strong></td><td align="left" valign="top">Left-align, pad on right. Right-align, pad on left. Fill between leading sign or base indicator and value.</td></tr><tr align="left"><td align="left" valign="top"/><td align="left" valign="top"/></tr><tr align="left"><td align="left" valign="top"/><td align="left" valign="top"/></tr><tr align="left"><td align="left" valign="top"><strong>scientific fixed</strong></td><td align="left" valign="top">Indicates the display preference for floating-point output (scientific notation vs. fixed-point decimal).</td></tr><tr align="left"><td align="left" valign="top"/><td align="left" valign="top"/></tr></table></section><section><title><p>Manipulators with arguments</p></title><p>There are six standard manipulators, such as <strong>setw( )</strong>, that take arguments. These are defined in the header file &lt;<strong>iomanip&gt;</strong>, and are summarized in the following table.</p><table><tr align="left"><th align="left" valign="top">Manipulator</th><th align="left" valign="top">effect</th></tr><tr align="left"><td align="left" valign="top"><strong>setiosflags (fmtflags n)</strong></td><td align="left" valign="top">Equivalent to a call to <strong>setf(n)</strong>. The setting remains in effect until the next change, such as <strong>ios::setf( )</strong>.</td></tr><tr align="left"><td align="left" valign="top"><strong>resetiosflags(fmtflags n)</strong></td><td align="left" valign="top">Clears only the format flags specified by <strong>n</strong>. The setting remains in effect until the next change, such as <strong>ios::unsetf( )</strong>.</td></tr><tr align="left"><td align="left" valign="top"><strong>setbase(base n)</strong></td><td align="left" valign="top">Changes base to <strong>n</strong>, where <strong>n</strong> is 10, 8, or 16. (Anything else results in 0.) If <strong>n</strong> is zero, output is base 10, but input uses the C conventions: 10 is 10, 010 is 8, and 0xf is 15. You might as well use <strong>dec</strong>, <strong>oct</strong>, and <strong>hex</strong> for output.</td></tr><tr align="left"><td align="left" valign="top"><strong>setfill(char n)</strong></td><td align="left" valign="top">Changes the fill character to <strong>n</strong>, such as <strong>ios::fill( )</strong>.</td></tr><tr align="left"><td align="left" valign="top"><strong>setprecision(int n)</strong></td><td align="left" valign="top">Changes the precision to <strong>n</strong>, such as <strong>ios::precision( )</strong>.</td></tr><tr align="left"><td align="left" valign="top"><strong>setw(int n)</strong></td><td align="left" valign="top">Changes the field width to <strong>n</strong>, such as <strong>ios::width( )</strong>.</td></tr></table><p>If you’re doing a lot of formatting, you can see how using manipulators instead of calling stream member functions can clean up your code. As an example, here’s the program from the previous section rewritten to use the manipulators. (The <strong>D( )</strong> macro is removed to make it easier to read.)<sup>.</sup></p><p>//: C04:Manips.cpp</p><p>// Format.cpp using manipulators</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iomanip&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  ofstream trc("trace.out");</p><p>  int i = 47;</p><p>  float f = 2300114.414159;</p><p>  char* s = "Is there any more?";</p><empty-line/><p>  trc &lt;&lt; setiosflags(ios::unitbuf</p><p>           | ios::showbase | ios::uppercase</p><p>           | ios::showpos);</p><p>  trc &lt;&lt; i &lt;&lt; endl;</p><p>  trc &lt;&lt; hex &lt;&lt; i &lt;&lt; endl</p><p>      &lt;&lt; oct &lt;&lt; i &lt;&lt; endl;</p><p>  trc.setf(ios::left, ios::adjustfield);</p><p>  trc &lt;&lt; resetiosflags(ios::showbase)</p><p>      &lt;&lt; dec &lt;&lt; setfill('0');</p><p>  trc &lt;&lt; "fill char: " &lt;&lt; trc.fill() &lt;&lt; endl;</p><p>  trc &lt;&lt; setw(10) &lt;&lt; i &lt;&lt; endl;</p><p>  trc.setf(ios::right, ios::adjustfield);</p><p>  trc &lt;&lt; setw(10) &lt;&lt; i &lt;&lt; endl;</p><p>  trc.setf(ios::internal, ios::adjustfield);</p><p>  trc &lt;&lt; setw(10) &lt;&lt; i &lt;&lt; endl;</p><p>  trc &lt;&lt; i &lt;&lt; endl; // Without setw(10)</p><empty-line/><p>  trc &lt;&lt; resetiosflags(ios::showpos)</p><p>      &lt;&lt; setiosflags(ios::showpoint)</p><p>      &lt;&lt; "prec = " &lt;&lt; trc.precision() &lt;&lt; endl;</p><p>  trc.setf(ios::scientific, ios::floatfield);</p><p>  trc &lt;&lt; f &lt;&lt; resetiosflags(ios::uppercase) &lt;&lt; endl;</p><p>  trc.setf(ios::fixed, ios::floatfield);</p><p>  trc &lt;&lt; f &lt;&lt; endl;</p><p>  trc &lt;&lt; f &lt;&lt; endl;</p><p>  trc &lt;&lt; setprecision(20);</p><p>  trc &lt;&lt; "prec = " &lt;&lt; trc.precision() &lt;&lt; endl;</p><p>  trc &lt;&lt; f &lt;&lt; endl;</p><p>  trc.setf(ios::scientific, ios::floatfield);</p><p>  trc &lt;&lt; f &lt;&lt; endl;</p><p>  trc.setf(ios::fixed, ios::floatfield);</p><p>  trc &lt;&lt; f &lt;&lt; endl;</p><p>  trc &lt;&lt; f &lt;&lt; endl;</p><empty-line/><p>  trc &lt;&lt; setw(10) &lt;&lt; s &lt;&lt; endl;</p><p>  trc &lt;&lt; setw(40) &lt;&lt; s &lt;&lt; endl;</p><p>  trc.setf(ios::left, ios::adjustfield);</p><p>  trc &lt;&lt; setw(40) &lt;&lt; s &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>You can see that a lot of the multiple statements have been condensed into a single chained insertion. Notice the call to <strong>setiosflags( )</strong> in which the bitwise-OR of the flags is passed. This could also have been done with <strong>setf( )</strong> and <strong>unsetf( )</strong> as in the previous example<sup>.</sup></p><p>When using <strong>setw( )</strong> with an output stream, the output expression is formatted into a temporary string that is padded with the current fill character if needed, as determined by comparing the length of the formatted result to the argument of <strong>setw( )</strong>. In other words, <strong>setw( )</strong> affects the <emphasis>result string</emphasis> of a formatted output operation. Likewise, using <strong>setw( )</strong> with input streams only is meaningful when reading <emphasis>strings</emphasis>, as the following example makes clear.</p><p>//: C04:InputWidth.cpp</p><p>// Shows limitations of setw with input</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cmath&gt;</p><p>#include &lt;iomanip&gt;</p><p>#include &lt;limits&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  istringstream is("one 2.34 five");</p><p>  string temp;</p><p>  is &gt;&gt; setw(2) &gt;&gt; temp;</p><p>  assert(temp == "on");</p><p>  is &gt;&gt; setw(2) &gt;&gt; temp;</p><p>  assert(temp == "e");</p><p>  double x;</p><p>  is &gt;&gt; setw(2) &gt;&gt; x;</p><p>  double relerr = fabs(x - 2.34) / x;</p><p>  assert(relerr &lt;= numeric_limits&lt;double&gt;::epsilon());</p><p>} ///:~</p><empty-line/><p>If you attempt to read a string, <strong>setw( )</strong> will control the number of characters extracted quite nicely… up to a point. The first extraction gets two characters, but the second only gets one, even though we asked for two. That is because <strong>operator&gt;&gt;( )</strong> uses white space as a delimiter (unless you turn off the <strong>skipws</strong> flag). When trying to read a number, however, such as <strong>x</strong>, you cannot use <strong>setw( ) </strong>to limit the characters read. With input streams, use only <strong>setw( )</strong> for extracting strings<sup>.</sup></p></section><section><title><p>Creating manipulators</p></title><p>Sometimes you’d like to create your own manipulators, and it turns out to be remarkably simple. A zero-argument manipulator such as <strong>endl </strong>is simply a function that takes as its argument an <strong>ostream</strong> reference and returns an <strong>ostream</strong> reference. The declaration for <strong>endl</strong> is<sup>.</sup></p><p>ostream&amp; endl(ostream&amp;);</p><empty-line/><p>Now, when you say:<sup>.</sup></p><p>cout &lt;&lt; "howdy" &lt;&lt; endl;</p><empty-line/><p>the <strong>endl</strong> produces the <emphasis>address</emphasis> of that function. So the compiler asks, "Is there a function I can call that takes the address of a function as its argument?" Predefined functions in <strong>&lt;iostream&gt; </strong>do this; they’re called <emphasis>applicators</emphasis> (because they <emphasis>apply</emphasis> a function to a stream). The applicator calls its function argument, passing it the <strong>ostream</strong> object as its argument. You don’t need to know how applicators work to create your own manipulator; you only need to know that they exist. Nonetheless, they’re simple. Here’s the (simplified) code for an <strong>ostream</strong> applicator:</p><p>ostream&amp; ostream::operator&lt;&lt;(ostream&amp; (*pf)(ostream&amp;)) {</p><p>  return pf(*this);</p><p>}</p><empty-line/><p>The actual definition is a little more complicated since it involves templates, but this code illustrates the technique. When a function such as <strong>*pf</strong> (that takes a stream parameter and returns a stream reference) is inserted into a stream, this applicator function is called, which in turn executes the function to which <strong>pf</strong> points. Applicators for <strong>ios_base</strong>, <strong>basic_ios</strong>, <strong>basic_ostream</strong>, and <strong>basic_istream</strong> are predefined in the standard C++ library<sup>.</sup></p><p>To illustrate the process, here’s a trivial example that creates a manipulator called <strong>nl</strong> that is equivalent to just inserting a newline into a stream (i.e., no flushing of the stream occurs, as with <strong>endl</strong>):<sup>.</sup></p><p>//: C04:nl.cpp</p><p>// Creating a manipulator</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>ostream&amp; nl(ostream&amp; os) {</p><p>  return os &lt;&lt; '\n';</p><p>}</p><empty-line/><p>int main() {</p><p>  cout &lt;&lt; "newlines" &lt;&lt; nl &lt;&lt; "between" &lt;&lt; nl</p><p>       &lt;&lt; "each" &lt;&lt; nl &lt;&lt; "word" &lt;&lt; nl;</p><p>} ///:~</p><empty-line/><p>When you insert <strong>nl</strong> into an output stream, such as <strong>cout</strong>, the following sequence of calls ensues:</p><p>cout.operator&lt;&lt;(nl) &#xE8; nl(cout)</p><empty-line/><p>The expression</p><p>os &lt;&lt; '\n';</p><empty-line/><p>inside <strong>nl( )</strong> calls <strong>ostream::operator(char)</strong>, which of course returns the stream, which is what is ultimately returned from <strong>nl( )</strong>.<a l:href="#n45" type="note">[45]</a></p></section><section><title><p>Effectors</p></title><p>As you’ve seen, zero-argument manipulators are easy to create. But what if you want to create a manipulator that takes arguments? If you inspect the <strong>&lt;iomanip&gt;</strong> header, you’ll see a type called <strong>smanip</strong>, which is what the manipulators with arguments return. You might be tempted to somehow use that type to define your own manipulators, but don’t give in to the temptation. The <strong>smanip</strong> type is implementation-dependent, so using it would not be portable. Fortunately, you can define such manipulators in a straightforward way without any special machinery, based on a technique introduced by Jerry Schwarz, called an <emphasis>effector</emphasis>.<a l:href="#n46" type="note">[46]</a> An effector is a simple class whose constructor formats a string representing the desired operation, along with an overloaded <strong>operator&lt;&lt;</strong> to insert that string into a stream. Here’s an example with two effectors. The first outputs a truncated character string, and the second prints a number in binary<sup>.</sup></p><p>//: C04:Effector.cpp</p><p>// Jerry Schwarz's "effectors"</p><p>#include &lt;cassert&gt;</p><p>#include &lt;limits&gt;  // For max()</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>// Put out a prefix of a string:</p><p>class Fixw {</p><p>  string str;</p><p>public:</p><p>  Fixw(const string&amp; s, int width)</p><p>    : str(s, 0, width) {}</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Fixw&amp; fw) {</p><p>    return os &lt;&lt; fw.str;</p><p>  }</p><p>};</p><empty-line/><p>// Print a number in binary:</p><p>typedef unsigned long ulong;</p><p>class Bin {</p><p>  ulong n;</p><p>public:</p><p>  Bin(ulong nn) { n = nn; }</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Bin&amp; b) {</p><p>    const ulong ULMAX = numeric_limits&lt;ulong&gt;::max();</p><p>    ulong bit = ~(ULMAX &gt;&gt; 1); // Top bit set</p><p>    while(bit) {</p><p>      os &lt;&lt; (b.n &amp; bit ? '1' : '0');</p><p>      bit &gt;&gt;= 1;</p><p>    }</p><p>    return os;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  string words =</p><p>    "Things that make us happy, make us wise";</p><p>  for(int i = words.size(); --i &gt;= 0;) {</p><p>    ostringstream s;</p><p>    s &lt;&lt; Fixw(words, i);</p><p>    assert(s.str() == words.substr(0, i));</p><p>  }</p><p>  ostringstream xs, ys;</p><p>  xs &lt;&lt; Bin(0xCAFEBABEUL);</p><p>  assert(xs.str() ==</p><p>    "1100""1010""1111""1110""1011""1010""1011""1110");</p><p>  ys &lt;&lt; Bin(0x76543210UL);</p><p>  assert(ys.str() ==</p><p>    "0111""0110""0101""0100""0011""0010""0001""0000");</p><p>} ///:~</p><empty-line/><p>The constructor for <strong>Fixw</strong> creates a shortened copy of its <strong>char*</strong> argument, and the destructor releases the memory created for this copy. The overloaded <strong>operator&lt;&lt;</strong> takes the contents of its second argument, the <strong>Fixw</strong> object, inserts it into the first argument, the <strong>ostream</strong>, and then returns the <strong>ostream</strong> so that it can be used in a chained expression. When you use <strong>Fixw</strong> in an expression like this:<sup>.</sup></p><p>cout &lt;&lt; Fixw(string, i) &lt;&lt; endl;</p><empty-line/><p>a <emphasis>temporary object</emphasis> is created by the call to the <strong>Fixw</strong> constructor, and that temporary object is passed to <strong>operator&lt;&lt;</strong>. The effect is that of a manipulator with arguments. The temporary <strong>Fixw</strong> object persists until the end of the statement<sup>.</sup></p><p>The <strong>Bin</strong> effector relies on the fact that shifting an unsigned number to the right shifts zeros into the high bits. We use <strong>numeric_limits&lt;unsigned long&gt;::max( )</strong> (the largest <strong>unsigned long</strong> value, from the standard header <strong>&lt;limits&gt;</strong> ) to produce a value with the high bit set, and this value is moved across the number in question (by shifting it to the right), masking each bit in turn. We’ve juxtaposed string literals in the code for readability; the separate strings are of course concatenated into one by the compiler<sup>.</sup></p><p>Historically, the problem with this technique was that once you created a class called <strong>Fixw</strong> for <strong>char*</strong> or <strong>Bin </strong>for <strong>unsigned long</strong>, no one else could create a different <strong>Fixw</strong> or <strong>Bin </strong>class for their type. However, with namespaces, this problem is eliminated<sup>.</sup></p></section></section><section><title><p>Iostream examples</p></title><section><p>In this section you’ll see some examples of what you can do with all the information you’ve learned in this chapter. Although many tools exist to manipulate bytes (stream editors such as <strong>sed</strong> and <strong>awk</strong> from UNIX are perhaps the most well known, but a text editor also fits this category), they generally have some limitations. Both <strong>sed</strong> and <strong>awk</strong> can be slow and can only handle lines in a forward sequence, and text editors usually require human interaction, or at least learning a proprietary macro language. The programs you write with iostreams have none of these limitations: they’re fast, portable, and flexible<sup>.</sup></p></section><section><title><p>Maintaining class library source code</p></title><p>Generally, when you create a class, you think in library terms: you make a header file <strong>Name.h </strong>for the class declaration, and you create a file in which the member functions are implemented, called <strong>Name.cpp</strong>. These files have certain requirements: a particular coding standard (the program shown here uses the coding format for this book), and in the header file the declarations are generally surrounded by some preprocessor statements to prevent multiple declarations of classes. (Multiple declarations confuse the compiler—it doesn’t know which one you want to use. They could be different, so it throws up its hands and gives an error message.)<sup>.</sup></p><p>This example allows you to create a new header/implementation pair of files or to modify an existing pair. If the files already exist, it checks and potentially modifies the files, but if they don’t exist, it creates them using the proper format<sup>.</sup></p><p>//: C04:Cppcheck.cpp</p><p>// Configures .h &amp; .cpp files to conform to style</p><p>// standard. Tests existing files for conformance.</p><p>#include &lt;fstream&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>bool startsWith(const string&amp; base, const string&amp; key) {</p><p>  return base.compare(0, key.size(), key) == 0;</p><p>}</p><empty-line/><p>void cppCheck(string fileName) {</p><p>  enum bufs { BASE, HEADER, IMPLEMENT,</p><p>    HLINE1, GUARD1, GUARD2, GUARD3,</p><p>    CPPLINE1, INCLUDE, BUFNUM };</p><p>  string part[BUFNUM];</p><p>  part[BASE] = fileName;</p><p>  // Find any '.' in the string:</p><p>  size_t loc = part[BASE].find('.');</p><p>  if(loc != string::npos)</p><p>    part[BASE].erase(loc); // Strip extension</p><p>  // Force to upper case:</p><p>  for(size_t i = 0; i &lt; part[BASE].size(); i++)</p><p>    part[BASE][i] = toupper(part[BASE][i]);</p><p>  // Create file names and internal lines:</p><p>  part[HEADER] = part[BASE] + ".h";</p><p>  part[IMPLEMENT] = part[BASE] + ".cpp";</p><p>  part[HLINE1] = "//" ": " + part[HEADER];</p><p>  part[GUARD1] = "#ifndef " + part[BASE] + "_H";</p><p>  part[GUARD2] = "#define " + part[BASE] + "_H";</p><p>  part[GUARD3] = "#endif // " + part[BASE] +"_H";</p><p>  part[CPPLINE1] = string("//") + ": "</p><p>    + part[IMPLEMENT];</p><p>  part[INCLUDE] = "#include \"" + part[HEADER] + "\"";</p><p>  // First, try to open existing files:</p><p>  ifstream existh(part[HEADER].c_str()),</p><p>           existcpp(part[IMPLEMENT].c_str());</p><p>  if(!existh) { // Doesn't exist; create it</p><p>    ofstream newheader(part[HEADER].c_str());</p><p>    assure(newheader, part[HEADER].c_str());</p><p>    newheader &lt;&lt; part[HLINE1] &lt;&lt; endl</p><p>      &lt;&lt; part[GUARD1] &lt;&lt; endl</p><p>      &lt;&lt; part[GUARD2] &lt;&lt; endl &lt;&lt; endl</p><p>      &lt;&lt; part[GUARD3] &lt;&lt; endl;</p><p>  } else { // Already exists; verify it</p><p>    stringstream hfile; // Write &amp; read</p><p>    ostringstream newheader; // Write</p><p>    hfile &lt;&lt; existh.rdbuf();</p><p>    // Check that first three lines conform:</p><p>    bool changed = false;</p><p>    string s;</p><p>    hfile.seekg(0);</p><p>    getline(hfile, s);</p><p>    bool lineUsed = false;</p><p>    // The call to good() is for Microsoft (later too)</p><p>    for (int line = HLINE1; hfile.good() &amp;&amp; line &lt;= GUARD2;</p><p>         ++line) {</p><p>      if(startsWith(s, part[line])) {</p><p>        newheader &lt;&lt; s &lt;&lt; endl;</p><p>        lineUsed = true;</p><p>        if (getline(hfile, s))</p><p>          lineUsed = false;</p><p>      } else {</p><p>        newheader &lt;&lt; part[line] &lt;&lt; endl;</p><p>        changed = true;</p><p>        lineUsed = false;</p><p>      }</p><p>    }</p><p>    // Copy rest of file</p><p>    if (!lineUsed)</p><p>      newheader &lt;&lt; s &lt;&lt; endl;</p><p>    newheader &lt;&lt; hfile.rdbuf();</p><p>    // Check for GUARD3</p><p>    string head = hfile.str();</p><p>    if(head.find(part[GUARD3]) == string::npos) {</p><p>      newheader &lt;&lt; part[GUARD3] &lt;&lt; endl;</p><p>      changed = true;</p><p>    }</p><p>    // If there were changes, overwrite file:</p><p>    if(changed) {</p><p>      existh.close();</p><p>      ofstream newH(part[HEADER].c_str());</p><p>      assure(newH, part[HEADER].c_str());</p><p>      newH &lt;&lt; "//@//\n"  // Change marker</p><p>        &lt;&lt; newheader.str();</p><p>    }</p><p>  }</p><p>  if(!existcpp) { // Create cpp file</p><p>    ofstream newcpp(part[IMPLEMENT].c_str());</p><p>    assure(newcpp, part[IMPLEMENT].c_str());</p><p>    newcpp &lt;&lt; part[CPPLINE1] &lt;&lt; endl</p><p>      &lt;&lt; part[INCLUDE] &lt;&lt; endl;</p><p>  } else { // Already exists; verify it</p><p>    stringstream cppfile;</p><p>    ostringstream newcpp;</p><p>    cppfile &lt;&lt; existcpp.rdbuf();</p><p>    // Check that first two lines conform:</p><p>    bool changed = false;</p><p>    string s;</p><p>    cppfile.seekg(0);</p><p>    getline(cppfile, s);</p><p>    bool lineUsed = false;</p><p>    for (int line = CPPLINE1;</p><p>         cppfile.good() &amp;&amp; line &lt;= INCLUDE;</p><p>         ++line) {</p><p>      if(startsWith(s, part[line])) {</p><p>        newcpp &lt;&lt; s &lt;&lt; endl;</p><p>        lineUsed = true;</p><p>        if (getline(cppfile, s))</p><p>          lineUsed = false;</p><p>      } else {</p><p>        newcpp &lt;&lt; part[line] &lt;&lt; endl;</p><p>        changed = true;</p><p>        lineUsed = false;</p><p>      }</p><p>    }</p><p>    // Copy rest of file</p><p>    if (!lineUsed)</p><p>      newcpp &lt;&lt; s &lt;&lt; endl;</p><p>    newcpp &lt;&lt; cppfile.rdbuf();</p><p>    // If there were changes, overwrite file:</p><p>    if(changed){</p><p>      existcpp.close();</p><p>      ofstream newCPP(part[IMPLEMENT].c_str());</p><p>      assure(newCPP, part[IMPLEMENT].c_str());</p><p>      newCPP &lt;&lt; "//@//\n"  // Change marker</p><p>        &lt;&lt; newcpp.str();</p><p>    }</p><p>  }</p><p>}</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  if(argc &gt; 1)</p><p>    cppCheck(argv[1]);</p><p>  else</p><p>    cppCheck("cppCheckTest.h");</p><p>} ///:~</p><empty-line/><p>First notice the useful function <strong>startsWith( )</strong>, which does just what its name says—it returns <strong>true</strong> if the first string argument starts with the second argument. This is used when looking for the expected comments and include-related statements. Having the array of strings, <strong>part</strong>, allows for easy looping through the series of expected statements in source code. If the source file doesn’t exist, we merely write the statements to a new file of the given name. If the file does exist, we search a line at a time, verifying that the expected lines occur. If they are not present, they are inserted. Special care has to be taken to make sure we don’t drop existing lines (see where we use the Boolean variable <strong>lineUsed</strong>). Notice that we use a <strong>stringstream</strong> for an existing file, so we can first write the contents of the file to it and then read from it and search it<sup>.</sup></p><p>The names in the enumeration are <strong>BASE</strong>, the capitalized base file name without extension; <strong>HEADER</strong>, the header file name; <strong>IMPLEMENT</strong>, the implementation file (<strong>cpp</strong>) name; <strong>HLINE1</strong>, the skeleton first line of the header file; <strong>GUARD1</strong>, <strong>GUARD2</strong>, and <strong>GUARD3</strong>, the "guard" lines in the header file (to prevent multiple inclusion); <strong>CPPLINE1</strong>, the skeleton first line of the <strong>cpp</strong> file; and <strong>INCLUDE</strong>, the line in the <strong>cpp</strong> file that includes the header file<sup>.</sup></p><p>If you run this program without any arguments, the following two files are created:</p><p>// CPPCHECKTEST.h</p><p>#ifndef CPPCHECKTEST_H</p><p>#define CPPCHECKTEST_H</p><empty-line/><p>#endif // CPPCHECKTEST_H</p><empty-line/><p>// CPPCHECKTEST.cpp</p><p>#include "CPPCHECKTEST.h"</p><empty-line/><p>(We removed the colon after the double-slash in the first comment lines so as not to confuse the book’s code extractor. It will appear in the actual output produced by <strong>cppCheck.</strong>)</p><p>You can experiment by removing selected lines from these files and re-running the program. Each time you will see that the correct lines are added back in. When a file is modified, the string "//@//" is placed as the first line of the file to bring the change to your attention. You will need to remove this line before you process the file again (otherwise <strong>cppcheck</strong> will assume the initial comment line is missing)<sup>.</sup></p></section><section><title><p>Detecting compiler errors</p></title><p>All the code in this book is designed to compile as shown without errors. Any line of code that should generate a compile-time error is commented out with the special comment sequence "//!". The following program will remove these special comments and append a numbered comment to the line. When you run your compiler, it should generate error messages, and you will see all the numbers appear when you compile all the files. This program also appends the modified line to a special file so that you can easily locate any lines that don’t generate errors<sup>.</sup></p><p>//: C04:Showerr.cpp</p><p>// Un-comment error generators</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;cstdio&gt;</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>const string usage =</p><p>  "usage: showerr filename chapnum\n"</p><p>  "where filename is a C++ source file\n"</p><p>  "and chapnum is the chapter name it's in.\n"</p><p>  "Finds lines commented with //! and removes\n"</p><p>  "comment, appending //(#) where # is unique\n"</p><p>  "across all files, so you can determine\n"</p><p>  "if your compiler finds the error.\n"</p><p>  "showerr /r\n"</p><p>  "resets the unique counter.";</p><empty-line/><p>class Showerr {</p><p>  const int CHAP;</p><p>  const string MARKER, FNAME;</p><p>  // File containing error number counter:</p><p>  const string ERRNUM;</p><p>  // File containing error lines:</p><p>  const string ERRFILE;</p><p>  stringstream edited; // Edited file</p><p>  int counter;</p><p>public:</p><p>  Showerr(const string&amp; f, const string&amp; en,</p><p>    const string&amp; ef, int c) : FNAME(f), MARKER("//!"),</p><p>    ERRNUM(en), ERRFILE(ef), CHAP(c) { counter = 0; }</p><p>  void replaceErrors() {</p><p>    ifstream infile(FNAME.c_str());</p><p>    assure(infile, FNAME.c_str());</p><p>    ifstream count(ERRNUM.c_str());</p><p>    if(count) count &gt;&gt; counter;</p><p>    int linecount = 1;</p><p>    string buf;</p><p>    ofstream errlines(ERRFILE.c_str(), ios::app);</p><p>    assure(errlines, ERRFILE.c_str());</p><p>    while(getline(infile, buf)) {</p><p>      // Find marker at start of line:</p><p>      size_t pos = buf.find(MARKER);</p><p>      if(pos != string::npos) {</p><p>        // Erase marker:</p><p>        buf.erase(pos, MARKER.size() + 1);</p><p>        // Append counter &amp; error info:</p><p>        ostringstream out;</p><p>        out &lt;&lt; buf &lt;&lt; " // (" &lt;&lt; ++counter &lt;&lt; ") "</p><p>            &lt;&lt; "Chapter " &lt;&lt; CHAP</p><p>            &lt;&lt; " File: " &lt;&lt; FNAME</p><p>            &lt;&lt; " Line " &lt;&lt; linecount &lt;&lt; endl;</p><p>        edited &lt;&lt; out.str();</p><p>        errlines &lt;&lt; out.str(); // Append error file</p><p>      }</p><p>      else</p><p>        edited &lt;&lt; buf &lt;&lt; "\n"; // Just copy</p><p>      linecount++;</p><p>    }</p><p>  }</p><p>  void saveFiles() {</p><p>    ofstream outfile(FNAME.c_str()); // Overwrites</p><p>    assure(outfile, FNAME.c_str());</p><p>    outfile &lt;&lt; edited.rdbuf();</p><p>    ofstream count(ERRNUM.c_str()); // Overwrites</p><p>    assure(count, ERRNUM.c_str());</p><p>    count &lt;&lt; counter; // Save new counter</p><p>  }</p><p>};</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  const string ERRCOUNT("../errnum.txt"),</p><p>    ERRFILE("../errlines.txt");</p><p>  requireMinArgs(argc, 1, usage.c_str());</p><p>  if(argv[1][0] == '/' || argv[1][0] == '-') {</p><p>    // Allow for other switches:</p><p>    switch(argv[1][1]) {</p><p>      case 'r': case 'R':</p><p>        cout &lt;&lt; "reset counter" &lt;&lt; endl;</p><p>        remove(ERRCOUNT.c_str()); // Delete files</p><p>        remove(ERRFILE.c_str());</p><p>        return 0;</p><p>      default:</p><p>        cerr &lt;&lt; usage &lt;&lt; endl;</p><p>        return 1;</p><p>    }</p><p>  }</p><p>  if (argc == 3) {</p><p>    Showerr s(argv[1], ERRCOUNT, ERRFILE, atoi(argv[2]));</p><p>    s.replaceErrors();</p><p>    s.saveFiles();</p><p>  }</p><p>} ///:~</p><empty-line/><p>You can replace the marker with one of your choice<sup>.</sup></p><p>Each file is read a line at a time, and each line is searched for the marker appearing at the head of the line; the line is modified and put into the error line list and into the string stream, <strong>edited</strong>. When the whole file is processed, it is closed (by reaching the end of a scope), it is reopened as an output file, and <strong>edited</strong> is poured into the file. Also notice the counter is saved in an external file. The next time this program is invoked, it continues to sequence the counter<sup>.</sup></p></section><section><title><p>A simple data logger</p></title><section><p>This example shows an approach you might take to log data to disk and later retrieve it for processing. It is meant to produce a temperature-depth profile of the ocean at various points. To hold the data, a class is used:<sup>.</sup></p><p>//: C04:DataLogger.h</p><p>// Datalogger record layout</p><p>#ifndef DATALOG_H</p><p>#define DATALOG_H</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iosfwd&gt;</p><p>#include &lt;string&gt;</p><p>using std::ostream;</p><empty-line/><p>struct Coord {</p><p>  int deg, min, sec;</p><p>  Coord(int d = 0, int m = 0, int s = 0)</p><p>    : deg(d), min(m), sec(s) {}</p><p>  std::string toString() const;</p><p>};</p><p>ostream&amp; operator&lt;&lt;(ostream&amp;, const Coord&amp;);</p><empty-line/><p>class DataPoint {</p><p>  std::time_t timest&amp; // Time &amp; day</p><p>  Coord latitude, longitude;</p><p>  double depth, temperature;</p><p>public:</p><p>  DataPoint(std::time_t ts, const Coord&amp; lat,</p><p>            const Coord&amp; lon, double dep, double temp)</p><p>    : timestamp(ts), latitude(lat), longitude(lon),</p><p>      depth(dep), temperature(temp) {}</p><p>  DataPoint() : timestamp(0), depth(0), temperature(0) {}</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp;, const DataPoint&amp;);</p><p>};</p><p>#endif // DATALOG_H ///:~</p><empty-line/><p>A <strong>DataPoint</strong> consists of a time stamp, which is stored as a <strong>time</strong>_t value as defined in <strong>&lt;ctime&gt;</strong>, longitude and latitude coordinates, and values for depth and temperature. We use inserters for easy formatting. Here’s the implementation file:<sup>.</sup></p><p>//: C04:DataLogger.cpp {O}</p><p>// Datapoint implementations</p><p>#include "DataLogger.h"</p><p>#include &lt;iomanip&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>ostream&amp; operator&lt;&lt;(ostream&amp; os, const Coord&amp; c) {</p><p>  return os &lt;&lt; c.deg &lt;&lt; '*' &lt;&lt; c.min &lt;&lt; '\''</p><p>            &lt;&lt; c.sec &lt;&lt; '"';</p><p>}</p><empty-line/><p>string Coord::toString() const {</p><p>  ostringstream os;</p><p>  os &lt;&lt; *this;</p><p>  return os.str();</p><p>}</p><empty-line/><p>ostream&amp; operator&lt;&lt;(ostream&amp; os, const DataPoint&amp; d) {</p><p>  os.setf(ios::fixed, ios::floatfield);</p><p>  char fillc = os.fill('0'); // Pad on left with '0'</p><p>  tm* tdata = localtime(&amp;d.timestamp);</p><p>  os &lt;&lt; setw(2) &lt;&lt; tdata-&gt;tm_mon + 1 &lt;&lt; '\\'</p><p>     &lt;&lt; setw(2) &lt;&lt; tdata-&gt;tm_mday &lt;&lt; '\\'</p><p>     &lt;&lt; setw(2) &lt;&lt; tdata-&gt;tm_year+1900 &lt;&lt; ' '</p><p>     &lt;&lt; setw(2) &lt;&lt; tdata-&gt;tm_hour &lt;&lt; ':'</p><p>     &lt;&lt; setw(2) &lt;&lt; tdata-&gt;tm_min &lt;&lt; ':'</p><p>     &lt;&lt; setw(2) &lt;&lt; tdata-&gt;tm_sec;</p><p>  os.fill(' '); // Pad on left with ' '</p><p>  streamsize prec = os.precision(4);</p><p>  os &lt;&lt; " Lat:" &lt;&lt; setw(9) &lt;&lt; d.latitude.toString()</p><p>     &lt;&lt; ", Long:" &lt;&lt; setw(9) &lt;&lt; d.longitude.toString()</p><p>     &lt;&lt; ", depth:" &lt;&lt; setw(9) &lt;&lt; d.depth</p><p>     &lt;&lt; ", temp:" &lt;&lt; setw(9) &lt;&lt; d.temperature;</p><p>  os.fill(fillc);</p><p>  os.precision(prec);</p><p>  return os;</p><p>} ///:~</p><empty-line/><p>The <strong>Coord::toString( ) </strong>function is necessary because the <strong>DataPoint</strong> inserter calls <strong>setw( )</strong> before it prints the latitude and longitude. If we used the stream inserter for <strong>Coord</strong> instead, the width would only apply to the first insertion (that is, to <strong>Coord::deg</strong>), since width changes are always reset immediately. The call to <strong>setf( )</strong> causes the floating-point output to be fixed-precision, and <strong>precision( )</strong> sets the number of decimal places to four. Notice how we restore the fill character and precision to whatever they were before the inserter was called<sup>.</sup></p><p>To get the values from the time encoding stored in <strong>DataPoint::timestamp</strong>, we call the function <strong>std::localtime( )</strong>, which returns a static pointer to a <strong>tm</strong> object. The <strong>tm struct</strong> has the following layout:</p><p>struct tm {</p><p>  int tm_sec; // 0-59 seconds</p><p>  int tm_min; // 0-59 minutes</p><p>  int tm_hour; // 0-23 hours</p><p>  int tm_mday; // Day of month</p><p>  int tm_mon; // 0-11 months</p><p>  int tm_year; // Years since 1900</p><p>  int tm_wday; // Sunday == 0, etc.</p><p>  int tm_yday; // 0-365 day of year</p><p>  int tm_isdst; // Daylight savings?</p><p>};</p><empty-line/></section><section><section><title><p>Generating test data</p></title><p>Here’s a program that creates a file of test data in binary form (using <strong>write( )</strong>) and a second file in ASCII form using the <strong>DataPoint</strong> inserter. You can also print it out to the screen, but it’s easier to inspect in file form<sup>.</sup></p><p>//: C04:Datagen.cpp</p><p>// Test data generator</p><p>//{L} DataLogger</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;cstring&gt;</p><p>#include &lt;fstream&gt;</p><p>#include "../require.h"</p><p>#include "DataLogger.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  ofstream data("data.txt");</p><p>  assure(data, "data.txt");</p><p>  ofstream bindata("data.bin", ios::binary);</p><p>  assure(bindata, "data.bin");</p><p>  time_t timer;</p><p>  Coord lat(45,20,31);</p><p>  Coord lon(22,34,18);</p><p>  // Seed random number generator:</p><p>  srand(time(&amp;timer));</p><p>  for(int i = 0; i &lt; 100; i++, timer += 55) {</p><p>    // Zero to 199 meters:</p><p>    double newdepth  = rand() % 200;</p><p>    double fraction = rand() % 100 + 1;</p><p>    newdepth += 1.0 / fraction;</p><p>    double newtemp = 150 + rand()%200; // Kelvin</p><p>    fraction = rand() % 100 + 1;</p><p>    newtemp += 1.0 / fraction;</p><p>    const DataPoint d(timer, Coord(45,20,31),</p><p>       Coord(22,34,18), newdepth,</p><p>       newtemp);</p><p>    data &lt;&lt; d &lt;&lt; endl;</p><p>    bindata.write(reinterpret_cast&lt;const char*&gt;(&amp;d),</p><p>   sizeof(d));</p><p>  }</p><p>} ///:~</p><empty-line/><p>The file <strong>data.txt </strong>is created in the ordinary way as an ASCII file, but <strong>data.bin </strong>has the flag <strong>ios::binary</strong> to tell the constructor to set it up as a binary file. To illustrate the formatting used for the text file, here is the first line of <strong>data.txt</strong> (the line wraps because it’s longer than this page will allow):<sup>.</sup></p><p>07\28\2003 12:54:40 Lat:45*20'31", Long:22*34'18", depth:  16.0164, temp: 242.0122</p><empty-line/><p>The Standard C library function <strong>time( )</strong> updates the <strong>time_t</strong> value its argument points to with an encoding of the current time, which on most platforms is the number of seconds elapsed since 00:00:00 GMT, January 1 1970 (the dawning of the age of Aquarius?). The current time is also a convenient way to seed the random number generator with the Standard C library function <strong>srand( )</strong>, as is done here<sup>.</sup></p><p>After this, the <strong>timer</strong> is incremented by 55 seconds to give an interesting interval between readings in this simulation<sup>.</sup></p><p>The latitude and longitude used are fixed values to indicate a set of readings at a single location. Both the depth and the temperature are generated with the Standard C library <strong>rand( )</strong> function, which returns a pseudorandom number between zero and a platform-dependent constant, <strong>RAND_MAX</strong>, defined in <strong>&lt;cstdlib&gt;</strong> (usually the value of the platform’s largest unsigned integer). To put this in a desired range, use the remainder operator <strong>%</strong> and the upper end of the range. These numbers are integral; to add a fractional part, a second call to <strong>rand( )</strong> is made, and the value is inverted after adding one (to prevent divide-by-zero errors)<sup>.</sup></p><p>In effect, the <strong>data.bin </strong>file is being used as a container for the data in the program, even though the container exists on disk and not in RAM. To send the data out to the disk in binary form, <strong>write( )</strong> is used. The first argument is the starting address of the source block—notice it must be cast to a <strong>char*</strong> because that’s what <strong>write( )</strong> expects for narrow streams. The second argument is the number of characters to write, which in this case is the size of the <strong>DataPoint</strong> object (again, because we’re using <emphasis>narrow streams</emphasis>). Because no pointers are contained in <strong>DataPoint</strong>, there is no problem in writing the object to disk. If the object is more sophisticated, you must implement a scheme for <emphasis>serialization</emphasis>, which writes the data referred to by pointers and defines new pointers when read back in later. (We don’t talk about serialization in this volume—most vendor class libraries have some sort of serialization structure built into them.)<sup>.</sup></p></section><section><title><p>Verifying and viewing the data</p></title><p>To check the validity of the data stored in binary format, you can read it into memory with the <strong>read( )</strong> member function for input streams, and compare it to the text file created earlier by <strong>Datagen.cpp</strong>. The following example just writes the formatted results to <strong>cout</strong>, but you can redirect this to a file and then use a file comparison utility to verify that it is identical to the original<sup>.</sup></p><p>//: C04:Datascan.cpp</p><p>// Test data generator</p><p>//{L} DataLogger</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "DataLogger.h"</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  ifstream bindata("data.bin", ios::binary);</p><p>  assure(bindata, "data.bin");</p><p>  DataPoint d;</p><p>  while (bindata.read(reinterpret_cast&lt;char*&gt;(&amp;d),</p><p>         sizeof d))</p><p>    cout &lt;&lt; d &lt;&lt; endl;</p><p>} ///:~</p><empty-line/></section></section></section></section><section><title><p>Internationalization</p></title><section><p>The software industry is now a healthy, worldwide economic market, and applications that can run in various languages and cultures are in demand. As early as the late 1980s, the C Standards Committee added support for non-U.S. formatting conventions with their <emphasis>locale</emphasis> mechanism. A locale is a set of preferences for displaying certain entities such as dates and monetary quantities. In the 1990s, the C Standards Committee approved an addendum to Standard C that specified functions to handle <emphasis>wide characters</emphasis> (denoted by the type <strong>wchar_t</strong>), which allow support for character sets other than ASCII and its commonly used Western European extensions. Although the size of a wide character is not specified, some platforms implement them as 32-bit quantities, so they can hold the encodings specified by the Unicode Consortium, as well as mappings to multi-byte characters sets defined by Asian standards bodies. C++ has integrated support for both wide characters and locales into the iostreams library<sup>.</sup></p></section><section><title><p>Wide Streams</p></title><p>A <emphasis>wide stream</emphasis> is a simply a stream class that handles wide characters. All the examples so far (except for the last traits example in Chapter 3) have used <emphasis>narrow</emphasis> streams, meaning streams that hold instances of <strong>char</strong>. Since stream operations are essentially the same no matter the underlying character type, they are encapsulated generically as templates. As we mentioned earlier, all input streams, for example, are connected somehow to the <strong>basic_istream</strong> class template, which is defined as follows:</p><p>template&lt;class charT, class traits = char_traits&lt;charT&gt; &gt;</p><p>class basic_istream {…};</p><empty-line/><p>In fact, all input stream types are specializations of this template, according to the following type definitions:</p><p>typedef basic_istream&lt;char&gt; istream;</p><p>typedef basic_istream&lt;wchar_t&gt; wistream;</p><p>typedef basic_ifstream&lt;char&gt; ifstream;</p><p>typedef basic_ifstream&lt;wchar_t&gt; wifstream;</p><p>typedef basic_istringstream&lt;char&gt; istringstream;</p><p>typedef basic_istringstream&lt;wchar_t&gt; wistringstream;</p><empty-line/><p>All other stream types are defined in similar fashion.</p><p>In a "perfect" world, this is all you’d have to do to have streams of different character types. In reality, things aren’t that simple. The reason is that the character-processing functions provided for <strong>char</strong> and <strong>wchar_t</strong> don’t have the same names. To compare two narrow strings, for example, you use the <strong>strcmp( )</strong> function. For wide characters, that function is named <strong>wcscmp( )</strong>. (Remember these originated in C, which does not have function overloading, hence unique names are a must.) For this reason, a generic stream can’t just call <strong>strcmp( )</strong> in response to a comparison operator. There needs to be a way for the correct low-level functions to be called automatically<sup>.</sup></p><p>The principle that guides the solution is well known. You simply "factor out" the differences into a new abstraction. The operations you can perform on characters have been abstracted into the <strong>char_traits</strong> template, which has predefined specializations for char and <strong>wchar_t</strong>, as we discussed at the end of the previous chapter. To compare two strings, then, <strong>basic_string</strong> just calls <strong>traits::compare( )</strong> (remember that <strong>traits</strong> is the second template parameter), which in turn calls either <strong>strcmp( )</strong> or <strong>wcscmp( )</strong>, depending on which specialization is being used (transparent to <strong>basic_string</strong>, of course)<sup>.</sup></p><p>You only need to be concerned about <strong>char_traits</strong> if you access the low-level character processing functions; most of the time you don’t care. Consider, however, making your inserters and extractors more robust by defining them as templates, just in case someone wants to use them on a wide stream.</p><p>To illustrate, recall again the <strong>Date</strong> class inserter from the beginning of this chapter. We originally declared it as:</p><p>ostream&amp; operator&lt;&lt;(ostream&amp;, const Date&amp;);</p><empty-line/><p>This accommodates only narrow streams. To make it generic, we simply make it a template based on <strong>basic_ostream</strong>:</p><p>template&lt;class charT, class traits&gt;</p><p>std::basic_ostream&lt;charT, traits&gt;&amp;</p><p>operator&lt;&lt;(std::basic_ostream&lt;charT, traits&gt;&amp; os,</p><p>           const Date&amp; d) {</p><p>  charT fillc = os.fill(os.widen('0'));</p><p>  charT dash = os.widen('-');</p><p>  os &lt;&lt; setw(2) &lt;&lt; d.month &lt;&lt; dash</p><p>     &lt;&lt; setw(2) &lt;&lt; d.day &lt;&lt; dash</p><p>     &lt;&lt; setw(4) &lt;&lt; d.year;</p><p>  os.fill(fillc);</p><p>  return os;</p><p>}</p><empty-line/><p>Notice that we also have to replace <strong>char</strong> with the template parameter <strong>charT</strong> in the declaration of <strong>fillc</strong>, since it could be either <strong>char</strong> or <strong>wchar_t</strong>, depending on the template instantiation being used<sup>.</sup></p><p>Since you don’t know when you’re writing the template which type of stream you have, you need a way to automatically convert character literals to the correct size for the stream. This is the job of the <strong>widen( )</strong> member function. The expression <strong>widen('-')</strong>, for example, converts its argument to <strong>L’-’</strong> (the literal syntax equivalent to the conversion <strong>wchar_t(‘-’)</strong>) if the stream is a wide stream and leaves it alone otherwise. There is also a <strong>narrow( )</strong> function that converts to a <strong>char</strong> if needed<sup>.</sup></p><p>We can use <strong>widen( )</strong> to write a generic version of the <strong>nl</strong> manipulator we presented earlier in the chapter.</p><p>template&lt;class charT, class traits&gt;</p><p>basic_ostream&lt;charT,traits&gt;&amp;</p><p>nl(basic_ostream&lt;charT,traits&gt;&amp; os) {</p><p>  return os &lt;&lt; charT(os.widen('\n'));</p><p>}</p><empty-line/></section><section><title><p>Locales</p></title><p>Perhaps the most notable difference in typical numeric computer output from country to country is the punctuator used to separate the integer and fractional parts of a real number. In the United States, a period denotes a decimal point, but in much of the world, a comma is expected instead. It would be quite inconvenient to do all your own formatting for locale-dependent displays. Once again, creating an abstraction that handles these differences solves the problem.</p><p>That abstraction is the <emphasis>locale</emphasis>. All streams have an associated locale object that they use for guidance on how to display certain quantities for different cultural environments. A locale manages the categories of culture-dependent display rules, which are defined as follows:</p><table><tr align="left"><td align="left" valign="top">Category</td><td align="left" valign="top">Effect</td></tr><tr align="left"><td align="left" valign="top">collate</td><td align="left" valign="top">allows comparing strings according to different, supported collating sequences</td></tr><tr align="left"><td align="left" valign="top">ctype</td><td align="left" valign="top">abstracts the character classification and conversion facilities found in &lt;cctype&gt;</td></tr><tr align="left"><td align="left" valign="top">monetary</td><td align="left" valign="top">supports different displays of monetary quantities</td></tr><tr align="left"><td align="left" valign="top">numeric</td><td align="left" valign="top">supports different display formats of real numbers, including radix (decimal point) and grouping (thousands) separators</td></tr><tr align="left"><td align="left" valign="top">time</td><td align="left" valign="top">supports various international formats for display of date and time</td></tr><tr align="left"><td align="left" valign="top">messages</td><td align="left" valign="top">scaffolding to implement context-dependent message catalogs (such as for error messages in different languages)</td></tr></table><empty-line/><p>The following program illustrates basic locale behavior:</p><p>//: C04:Locale.cpp</p><p>//{-g++}</p><p>//{-bor}</p><p>//{-edg}</p><p>// Illustrates effects of locales</p><p>#include &lt;iostream&gt;</p><p>#include &lt;locale&gt;</p><p>using namespace std;</p><p>int main() {</p><p>  locale def;</p><p>  cout &lt;&lt; def.name() &lt;&lt; endl;</p><p>  locale current = cout.getloc();</p><p>  cout &lt;&lt; current.name() &lt;&lt; endl;</p><p>  float val = 1234.56;</p><p>  cout &lt;&lt; val &lt;&lt; endl;</p><p>  // Change to French/France</p><p>  cout.imbue(locale("french"));</p><p>  current = cout.getloc();</p><p>  cout &lt;&lt; current.name() &lt;&lt; endl;</p><p>  cout &lt;&lt; val &lt;&lt; endl;</p><empty-line/><p>  cout &lt;&lt; "Enter the literal 7890,12: ";</p><p>  cin.imbue(cout.getloc());</p><p>  cin &gt;&gt; val;</p><p>  cout &lt;&lt; val &lt;&lt; endl;</p><p>  cout.imbue(def);</p><p>  cout &lt;&lt; val &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>Here’s the output:</p><p>C</p><p>C</p><p>1234.56</p><p>French_France.1252</p><p>1234,56</p><p>Enter the literal 7890,12: <strong>7890,12</strong></p><p>7890,12</p><p>7890.12</p><empty-line/><p>The default locale is the "C" locale, which is what C and C++ programmers have been used to all these years (basically, English language and American culture). All streams are initially "imbued" with the "C" locale. The <strong>imbue( )</strong> member function changes the locale that a stream uses. Notice that the full ISO name for the "French" locale is displayed (that is, French used in France vs. French used in another country). This example shows that this locale uses a comma for a radix point in numeric display. We have to change <strong>cin</strong> to the same locale if we want to do input according to the rules of this locale.</p><p>Each locale category is divided into number of <emphasis>facets</emphasis>, which are classes encapsulating the functionality that pertains to that category. For example, the <strong>time</strong> category has the facets <strong>time_put</strong> and <strong>time_get</strong>, which contain functions for doing time and date <strong>input</strong> and <strong>output</strong> respectively. The <strong>monetary</strong> category has facets <strong>money_get</strong>, <strong>money_put</strong>, and <strong>moneypunct</strong>. (The latter facet determines the currency symbol.) The following program illustrates the <strong>moneypunct</strong> facet. (The <strong>time</strong> facet requires a sophisticated use of iterators which is beyond the scope of this chapter.)</p><p>//: C04:Facets.cpp</p><p>//{-bor}</p><p>//{-g++}</p><p>#include &lt;iostream&gt;</p><p>#include &lt;locale&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  // Change to French/France</p><p>  locale loc("french");</p><p>  cout.imbue(loc);</p><empty-line/><p>  string currency =</p><p>    use_facet&lt;moneypunct&lt;char&gt; &gt;(loc).curr_symbol();</p><p>  char point =</p><p>    use_facet&lt;moneypunct&lt;char&gt; &gt;(loc).decimal_point();</p><p>  cout &lt;&lt; "I made " &lt;&lt; currency &lt;&lt; 12.34 &lt;&lt; " today!"</p><p>       &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The output shows the French currency symbol and decimal separator:</p><p>I made &#xC7;12,34 today!</p><empty-line/><p>You can also define your own facets to construct customized locales.<a l:href="#n47" type="note">[47]</a> Be aware that the overhead for locales is considerable. In fact, some library vendors provide different "flavors" of the standard C++ library to accommodate environments that have limited space.<a l:href="#n48" type="note">[48]</a></p></section></section><section><title><p>Summary</p></title><p>This chapter has given you a fairly thorough introduction to the iostream class library. In all likelihood, it is all you need to create programs using iostreams. However, be aware that some additional features in iostreams are not used often, but you can discover them by looking at the iostream header files and by reading your compiler’s documentation on iostreams or the references mentioned in this chapter and in the book’s preface<sup>.</sup></p></section><section><title><p>Exercises</p></title><p>             1.             Open a file by creating an <strong>ifstream</strong> object. Make an <strong>ostringstream</strong> object and read the entire contents into the <strong>ostringstream</strong> using the <strong>rdbuf( )</strong> member function. Extract a <strong>string</strong> copy of the underlying buffer and capitalize every character in the file using the Standard C <strong>toupper( )</strong> macro defined in <strong>&lt;cctype&gt;</strong>. Write the result out to a new file.&lt;/#&gt;&lt;#TIC2V2_CHAPTER5_I190&gt;</p><p>        24.             Create a program that opens a file (the first argument on the command line) and searches it for any one of a set of words (the remaining arguments on the command line). Read the input a line at a time, and write out the lines (with line numbers) that match to the new file.&lt;/#&gt;&lt;#TIC2V2_CHAPTER5_I191&gt;</p><p>        25.             Write a program that adds a copyright notice to the beginning of all source-code files indicated by the program’s command-line arguments.&lt;/#&gt;&lt;#TIC2V2_CHAPTER5_I192&gt;</p><p>        26.             Use your favorite text-searching program (<strong>grep</strong>, for example) to output the names (only) of all the files that contain a particular pattern. Redirect the output into a file. Write a program that uses the contents of that file to generate a batch file that invokes your editor on each of the files found by the search program.</p><p>         27.             We know that <strong>setw( )</strong> allows for a minimum of characters read in, but what if you wanted to read a maximum? Write an effector that allows the user to specify a maximum number of characters to extract. Have your effector also work for output, in such a way that output fields are truncated, if necessary, to stay within width limits.</p><p>        28.             Demonstrate to yourself that if the fail or bad bit is set, and you subsequently turn on stream exceptions, that the stream will immediately throw an exception.</p><p>        29.             String streams accommodate easy conversions, but they come with a price. Write a program that races <strong>atoi( )</strong> against the <strong>stringstream</strong> conversion system to see the effect of the overhead involved with <strong>stringstream</strong>.</p><p>        30.             Make a <strong>Person</strong> struct with fields such as name, age, address, etc. Make the string fields fixed-size arrays. The social security number will be the key for each record. Implement the following <strong>Database</strong> class.</p><empty-line/><p>class DataBase {</p><p>public:</p><p>  // Find where a record is on disk</p><p>  size_t query(size_t ssn);</p><p>  // Return the person at rn (record number)</p><p>  Person retrieve(size_t rn);</p><p>  // Record a record on disk</p><p>  void add(const Person&amp; p);</p><p>};</p><empty-line/><p>Write some <strong>Person</strong> records to disk (do not keep them all in memory). When the user requests a record, read it off the disk and return it. The I/O operations in the <strong>DataBase</strong> class use <strong>read( )</strong> and <strong>write( )</strong> to process all <strong>Person</strong> records.</p><p>         31.             Write an <strong>operator&lt;&lt;</strong> inserter for the <strong>Person</strong> struct that can be used to display records in a format easily read. Practice writing it out to file.</p><p>        32.             Suppose your database for your <strong>Person</strong> structs was lost but that you have the file you wrote from the previous exercise. Recreate your database using this file. Be sure to use error checking.</p><p>        33.             Write <strong>size_t(-1)</strong> (the largest <strong>unsigned int</strong> on your platform) to a text file 1,000,000 times. Repeat, but write to a binary file. Compare the two files for size, and see how much room is saved using the binary format. (You may first want to try to calculate how much will be saved on your platform.)</p><p>        34.             Found out the maximum number of digits of precision your implementation of iostreams will print by repeatedly increasing the value of the argument to <strong>precision( )</strong> when printing a transcendental number such as <strong>sqrt(2.0)</strong>.</p><p>        35.             Write a program that reads real numbers from a file and prints their sum, average, minimum, and maximum.</p><p>        36.             Determine the output of the following program before it is executed.</p><p>//: C04:Exercise16.cpp</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;sstream&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><p>#define d(a) cout &lt;&lt; #a " ==\t" &lt;&lt; a &lt;&lt; endl;</p><empty-line/><p>void tellPointers(fstream&amp; s) {</p><p>  d(s.tellp());</p><p>  d(s.tellg());</p><p>  cout &lt;&lt; endl;</p><p>}</p><p>void tellPointers(stringstream&amp; s) {</p><p>  d(s.tellp());</p><p>  d(s.tellg());</p><p>  cout &lt;&lt; endl;</p><p>}</p><p>int main() {</p><p>  fstream in("Exercise16.cpp");</p><p>  assure(in, "Exercise16.cpp");</p><p>  in.seekg(10);</p><p>  tellPointers(in);</p><p>  in.seekp(20);</p><p>  tellPointers(in);</p><p>  stringstream memStream("Here is a sentence.");</p><p>  memStream.seekg(10);</p><p>  tellPointers(memStream);</p><p>  memStream.seekp(5);</p><p>  tellPointers(memStream);</p><p>} ///:~</p><empty-line/><p>         37.             Suppose you are given line-oriented data in a file formatted as follows:</p><p>Australia</p><p>5E56,7667230284,Langler,Tyson,31.2147,0.00042117361</p><p>2B97,7586701,Oneill,Zeke,553.429,0.0074673053156065</p><p>4D75,7907252710,Nickerson,Kelly,761.612,0.010276276</p><p>9F2,6882945012,Hartenbach,Neil,47.9637,0.0006471644</p><p>Austria</p><p>480F,7187262472,Oneill,Dee,264.012,0.00356226040013</p><p>1B65,4754732628,Haney,Kim,7.33843,0.000099015948475</p><p>DA1,1954960784,Pascente,Lester,56.5452,0.0007629529</p><p>3F18,1839715659,Elsea,Chelsy,801.901,0.010819887645</p><p>Belgium</p><p>BDF,5993489554,Oneill,Meredith,283.404,0.0038239127</p><p>5AC6,6612945602,Parisienne,Biff,557.74,0.0075254727</p><p>6AD,6477082,Pennington,Lizanne,31.0807,0.0004193544</p><p>4D0E,7861652688,Sisca,Francis,704.751,0.00950906238</p><p>Bahamas</p><p>37D8,6837424208,Parisienne,Samson,396.104,0.0053445</p><p>5E98,6384069,Willis,Pam,90.4257,0.00122009564059246</p><p>1462,1288616408,Stover,Hazal,583.939,0.007878970561</p><p>5FF3,8028775718,Stromstedt,Bunk,39.8712,0.000537974</p><p>1095,3737212,Stover,Denny,3.05387,0.000041205248883</p><p>7428,2019381883,Parisienne,Shane,363.272,0.00490155</p><empty-line/><p>The heading of each section is a region, and every line under that heading is a seller in that region. Each comma-separated field represents the data about each seller. The first field in a line is the SELLER_ID which unfortunately was written out in hexadecimal format. The second is the PHONE_NUMBER (notice that some are missing area codes). LAST_NAME and FIRST_NAME then follow. TOTAL_SALES is the second to the last column. The last column is the decimal amount of the total sales that the seller represents for the company. You are to format the data on the terminal window so that an executive can easily interpret the trends. Sample output is given below.            Australia</p><p>              ---------------------------------</p><empty-line/><p>*Last Name*   *First Name*   *ID*    *Phone*        *Sales*   *Percent*</p><empty-line/><p>Langler       Tyson          24150   766-723-0284     31.24   4.21E-02</p><p>Oneill        Zeke           11159   XXX-758-6701    553.43   7.47E-01</p><p>(etc.)</p></section></section><section><title><p>5: Templates in depth</p></title><section><p>The C++ template facility goes far beyond simple "containers of <strong>T</strong>." Although the original motivation was to enable type-safe, generic containers, in modern C++, templates are also used to generate custom code and to optimize program execution through compile-time programming constructs<sup>.</sup></p><p>In this chapter we offer a practical look at the power (and pitfalls) of programming with templates in modern C++. For a more complete analysis of template-related language issues and "gotchas," we recommend the superb book by David Vandevoorde and Nico Josuttis.<a l:href="#n49" type="note">[49]</a></p></section><section><title><p>Template parameters</p></title><section><p>As we illustrated in Volume 1, templates come in two flavors: function templates and class templates. Both are wholly characterized by their parameters. Each template parameter itself can represent one of the following categories of arguments:</p><p>1.       Types (either built-in or user-defined)</p><p>2.      Compile-time constant values (for example, integers, and pointers and references to static entities; often referred to as non-type parameters)</p><p>3.      Other templates</p><p>The examples in Volume 1 all fall into the first category and are the most common. The canonical example for simple container-like templates nowadays seems to be a <strong>Stack</strong> class. Being a container, a <strong>Stack</strong> object is not concerned with the type of object it stores; the logic of holding objects is independent of the type of objects being held. For this reason you can use a type parameter to represent the contained type:<sup>.</sup></p><p>template&lt;class T&gt;</p><p>class Stack {</p><p>  T* data;</p><p>  size_t count;</p><p>public:</p><p>  void push(const T&amp; t);</p><p>  // etc.</p><p>};</p><empty-line/><p>You provide the actual type to be used for a particular <strong>Stack</strong> instance by means of an argument for the parameter <strong>T</strong>:</p><p>Stack&lt;int&gt; myStack;  // A Stack of ints</p><empty-line/><p>The compiler then provides an <strong>int</strong>-version of <strong>Stack</strong> by substituting <strong>int</strong> for <strong>T</strong> and generating the corresponding code. The name of the class instance generated from the template in this case is <strong>Stack&lt;int&gt;</strong><sup><strong>.</strong></sup></p></section><section><title><p>Non-type template parameters</p></title><p>It is also possible to provide a non-type template parameter, as long as it represents an integral value that is known at compile time. You can make a fixed-size <strong>Stack</strong>, for instance, by specifying a non-type parameter to be used as the dimension for the underlying array, as follows<sup>.</sup></p><p>template&lt;class T, size_t N&gt;</p><p>class Stack {</p><p>  T data[N];  // Fixed capacity is N</p><p>  size_t count;</p><p>public:</p><p>  void push(const T&amp; t);</p><p>  // etc.</p><p>};</p><empty-line/><p>You must provide a compile-time constant value for the parameter <strong>N</strong> when you request an instance of this template, such as</p><p>Stack&lt;int, 100&gt; myFixedStack;</p><empty-line/><p>Because the value of <strong>N</strong> is known at compile time, the underlying array (<strong>data</strong>) can be placed on the runtime stack instead of on the free store, which can improve runtime performance by avoiding the overhead associated with dynamic memory allocation. Following the pattern mentioned earlier, the name of the class above is <strong>Stack&lt;int, 100&gt;</strong>. This means that each distinct value of <strong>N</strong> results in a unique class type. For example, <strong>Stack&lt;int, 99&gt;</strong> is a distinct class from <strong>Stack&lt;int, 100&gt;</strong><sup><strong>.</strong></sup></p><p>The <strong>bitset</strong> class template, discussed in detail in Chapter 7, is the only class in the standard C++ library that uses a non-type template parameter, which happens to specify the number of bits the <strong>bitset</strong> object can hold. The following random number generator example uses a <strong>bitset</strong> to track numbers so all the numbers in its range are returned in random order without repetition before starting over. This example also overloads <strong>operator( )</strong> to produce a familiar function-call syntax<sup>.</sup></p><p>//: C05:Urand.h</p><p>//{-bor}</p><p>// Unique randomizer</p><p>#ifndef URAND_H</p><p>#define URAND_H</p><p>#include &lt;bitset&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>using std::size_t;</p><p>using std::bitset;</p><empty-line/><p>template&lt;size_t UpperBound&gt;</p><p>class Urand {</p><p>  bitset&lt;UpperBound&gt; used;</p><p>public:</p><p>  Urand() {</p><p>    srand(time(0));  // randomize</p><p>  }</p><p>  size_t operator()(); // The "generator" function</p><p>};</p><empty-line/><p>template&lt;size_t UpperBound&gt;</p><p>inline size_t Urand&lt;UpperBound&gt;::operator()() {</p><p>  if(used.count() == UpperBound)</p><p>    used.reset();  // start over (clear bitset)</p><p>  size_t newval;</p><p>  while(used[newval = rand() % UpperBound])</p><p>    ; // Until unique value is found</p><p>  used[newval] = true;</p><p>  return newval;</p><p>}</p><p>#endif // URAND_H ///:~</p><empty-line/><p>The uniqueness of <strong>Urand</strong> is produced by tracking with a <strong>bitset</strong> all the numbers possible in the random space (the upper bound is set with the template argument) and by recording each number as it’s used by setting the corresponding position bit in <strong>used</strong>. When the numbers are all used up, the <strong>bitset</strong> is cleared to start over. Here’s a simple driver that illustrates how to use a <strong>Urand</strong> object:<sup>.</sup></p><p>//: C05:UrandTest.cpp</p><p>//{-bor}</p><p>#include &lt;iostream&gt;</p><p>#include "Urand.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  Urand&lt;10&gt; u;</p><p>  for(int i = 0; i &lt; 20; ++i)</p><p>    cout &lt;&lt; u() &lt;&lt; ' ';</p><p>} ///:~</p><empty-line/><p>As we explain later in this chapter, non-type template arguments are also important in the optimization of numeric computations<sup>.</sup></p></section><section><title><p>Default template arguments</p></title><p>You can provide default arguments for template parameters in class templates. (They are not allowed in function templates.) As with default function arguments, they should only be defined once, the first time a template declaration or definition is seen by the compiler; and once you introduce a default argument, all the subsequent template parameters must also have defaults. To make the fixed-size <strong>Stack</strong> template shown earlier a little friendlier, for example, you can add a default argument like this:<sup>.</sup></p><p>template&lt;class T, size_t N = 100&gt;</p><p>class Stack {</p><p>  T data[N];  // Fixed capacity is N</p><p>  size_t count;</p><p>public:</p><p>  void push(const T&amp; t);</p><p>  // etc.</p><p>};</p><empty-line/><p>Now, if you omit the second template argument when declaring a <strong>Stack</strong> object, the value for <strong>N</strong> will default to 100<sup>.</sup></p><p>You can choose to provide defaults for all arguments, but you must use an empty set of brackets when declaring an instance so that the compiler knows that a class template is involved. Here’s how:</p><p>template&lt;class T = int, size_t N = 100&gt;  // Both defaulted</p><p>class Stack {</p><p>  T data[N];  // Fixed capacity is N</p><p>  size_t count;</p><p>public:</p><p>  void push(const T&amp; t);</p><p>  // etc.</p><p>};</p><empty-line/><p>Stack&lt;&gt; myStack;  // Same as Stack&lt;int, 100&gt;<sup>.</sup></p><empty-line/><p>Default arguments are used heavily in the standard C++ library. The <strong>vector</strong> class template, for instance, is declared as follows:</p><p>template &lt;class T, class Allocator = allocator&lt;T&gt; &gt;</p><p>class vector;</p><empty-line/><p>Note the space between the last two right angle bracket characters. This prevents the compiler from interpreting those two characters (<strong>&gt;&gt;</strong>) as the right-shift operator.</p><p>This declaration reveals that <strong>vector</strong> actually takes two arguments: the type of the contained objects it holds, and a type that represents the allocator used by the vector. (We talk more about allocators in Chapter 7.) Whenever you omit the second argument, the standard <strong>allocator</strong> template is used, parameterized by the first template parameter. This declaration also shows that you can use template parameters in other, subsequent template parameters, as <strong>T</strong> is used here<sup>.</sup></p><p>Although you cannot use default template arguments in function templates, you can use template parameters as default arguments to normal functions. The following function template adds the elements in a sequence<sup>.</sup></p><p>//: C05:FuncDef.cpp</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T&gt;</p><p>T sum(T* b, T* e, T init = T()) {</p><p>  while(b != e)</p><p>    init += *b++;</p><p>  return init;</p><p>}</p><empty-line/><p>int main() {</p><p>  int a[] = {1,2,3};</p><p>  cout &lt;&lt; sum(a, a+sizeof a / sizeof a[0]) &lt;&lt; endl; // 6</p><p>} ///:~</p><empty-line/><p>The third argument to <strong>sum( )</strong> is the initial value for the accumulation of the elements. Since we omitted it, this argument defaults to <strong>T( )</strong>, which in the case of <strong>int</strong> and other built-in types invokes a pseudo-constructor that performs zero-initialization<sup>.</sup></p></section><section><title><p>Template template parameters</p></title><p>The third type of parameter a template can accept is another class template. This may sound strange, since templates are types, and type parameters are already allowed, but if you are going to use a template type parameter as a template in your code, the compiler needs to know that the parameter is a template in the first place. The following example illustrates a template template parameter<sup>.</sup></p><p>//: C05:TempTemp.cpp</p><p>// Illustrates a template template parameter</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T&gt;</p><p>class Array { // A simple, expandable sequence</p><p>  enum {INIT = 10};</p><p>  T *data;</p><p>  size_t capacity;</p><p>  size_t count;</p><p>public:</p><p>  Array() {</p><p>    count = 0;</p><p>    data = new T[capacity = INIT];</p><p>  }</p><p>  void push_back(const T&amp; t) {</p><p>    if(count == capacity) {</p><p>      // Grow underlying array</p><p>      size_t newCap = 2*capacity;</p><p>      T* newData = new T[newCap];</p><p>      for (size_t i = 0; i &lt; count; ++i)</p><p>        newData[i] = data[i];</p><p>      delete data;</p><p>      data = newData;</p><p>      capacity = newCap;</p><p>    }</p><p>    data[count++] = t;</p><p>  }</p><p>  void pop_back() {</p><p>    if(count &gt; 0)</p><p>      --count;</p><p>  }</p><p>  T* begin() {</p><p>    return data;</p><p>  }</p><p>  T* end() {</p><p>    return data + count;</p><p>  }</p><p>};</p><empty-line/><p>template&lt;class T, template&lt;class&gt; class Seq&gt;</p><p>class Container {</p><p>  Seq&lt;T&gt; seq;</p><p>public:</p><p>  void append(const T&amp; t) {</p><p>    seq.push_back(t);</p><p>  }</p><p>  T* begin() {</p><p>    return seq.begin();</p><p>  }</p><p>  T* end() {</p><p>    return seq.end();</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  Container&lt;int, Array&gt; theData;</p><p>  theData.append(1);</p><p>  theData.append(2);</p><p>  int* p = theData.begin();</p><p>  while(p != theData.end())</p><p>    cout &lt;&lt; *p++ &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The <strong>Array</strong> class template is a trivial sequence container. The <strong>Container</strong> template takes two parameters: the type of the objects it is to hold, and a sequence data structure to do the holding. The following line in the implementation of the <strong>Container</strong> class requires that we inform the compiler that <strong>Seq</strong> is a template:<sup>.</sup></p><p>  Seq&lt;T&gt; seq;</p><empty-line/><p>If we hadn’t declared <strong>Seq</strong> to be a template template parameter, the compiler would complain here that <strong>Seq</strong> is not a template, since we’re using it as such. In <strong>main( )</strong> a <strong>Container</strong> is instantiated to use an <strong>Array</strong> to hold integers, so <strong>Seq</strong> stands for <strong>Array</strong> in this example<sup>.</sup></p><p>Note that it is not necessary in this case to name the parameter for <strong>Seq</strong> inside <strong>Container</strong>’s declaration. The line in question is:</p><p>template&lt;class T, template&lt;class&gt; class Seq&gt;</p><empty-line/><p>Although we could have written</p><p>template&lt;class T, template&lt;class U&gt; class Seq&gt;</p><empty-line/><p>the parameter <strong>U</strong> is not needed anywhere. All that matters is that <strong>Seq</strong> is a class template that takes a single type parameter. This is analogous to omitting the names of function parameters when they’re not needed, such as when you overload the post-increment operator:<sup>.</sup></p><p>T operator++(int);</p><empty-line/><p>The <strong>int</strong> here is merely a placeholder and therefore needs no name.</p><p>The following program uses a fixed-size array, which has an extra template parameter representing the array dimension:</p><p>//: C05:TempTemp2.cpp</p><p>// A multi-variate template template parameter</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T, size_t N&gt;</p><p>class Array {</p><p>  T data[N];</p><p>  size_t count;</p><p>public:</p><p>  Array() { count = 0; }</p><p>  void push_back(const T&amp; t) {</p><p>    if(count &lt; N)</p><p>      data[count++] = t;</p><p>  }</p><p>  void pop_back() {</p><p>    if(count &gt; 0)</p><p>      --count;</p><p>  }</p><p>  T* begin() { return data; }</p><p>  T* end() { return data + count; }</p><p>};</p><empty-line/><p>template&lt;class T,size_t N,template&lt;class,size_t&gt; class Seq&gt;</p><p>class Container {</p><p>  Seq&lt;T,N&gt; seq;</p><p>public:</p><p>  void append(const T&amp; t) { seq.push_back(t); }</p><p>  T* begin() { return seq.begin(); }</p><p>  T* end() { return seq.end(); }</p><p>};</p><empty-line/><p>int main() {</p><p>  const size_t N = 10;</p><p>  Container&lt;int, N, Array&gt; theData;</p><p>  theData.append(1);</p><p>  theData.append(2);</p><p>  int* p = theData.begin();</p><p>  while(p != theData.end())</p><p>    cout &lt;&lt; *p++ &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>Once again, parameter names are not needed in the declaration of <strong>Seq</strong> inside <strong>Container</strong>’s declaration, but we need two parameters to declare the data member <strong>seq</strong>, hence the appearance of the non-type parameter <strong>N</strong> at the top level<sup>.</sup></p><p>Combining default arguments with template template parameters is slightly more problematic. The When the compiler looks at the inner parameters of a template template parameter, default arguments are not considered, so you have to repeat the defaults in order to get an exact match. The following example uses a default argument for the fixed-size <strong>Array</strong> template and shows how to accommodate this quirk in the language<sup>.</sup></p><p>//: C05:TempTemp3.cpp</p><p>//{-bor}</p><p>//{-msc}</p><p>// Combining template template parameters and</p><p>// default arguments</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T, size_t N = 10&gt;  // A default argument</p><p>class Array {</p><p>  T data[N];</p><p>  size_t count;</p><p>public:</p><p>  Array() { count = 0; }</p><p>  void push_back(const T&amp; t) {</p><p>    if(count &lt; N)</p><p>      data[count++] = t;</p><p>  }</p><p>  void pop_back() {</p><p>    if(count &gt; 0)</p><p>      --count;</p><p>  }</p><p>  T* begin() { return data; }</p><p>  T* end() { return data + count; }</p><p>};</p><empty-line/><p>template&lt;class T, template&lt;class, size_t = 10&gt; class Seq&gt;</p><p>class Container {</p><p>  Seq&lt;T&gt; seq;  // Default used</p><p>public:</p><p>  void append(const T&amp; t) { seq.push_back(t); }</p><p>  T* begin() { return seq.begin(); }</p><p>  T* end() { return seq.end(); }</p><p>};</p><empty-line/><p>int main() {</p><p>  Container&lt;int, Array&gt; theData;</p><p>  theData.append(1);</p><p>  theData.append(2);</p><p>  int* p = theData.begin();</p><p>  while(p != theData.end())</p><p>    cout &lt;&lt; *p++ &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>It is necessary to include the default dimension of 10 in the line:</p><p>template&lt;class T, template&lt;class, size_t = 10&gt; class Seq&gt;</p><empty-line/><p>Both the definition of <strong>seq</strong> in <strong>Container</strong> and <strong>theData</strong> in <strong>main( )</strong> use the default. The only way to use something other than the default value is as the previous program (<strong>TempTemp2.cpp</strong>) illustrated. This is the only exception to the rule stated earlier that default arguments should appear only once in a compilation unit<sup>.</sup></p><p>Since the standard sequence containers (<strong>vector</strong>, <strong>list</strong>, and <strong>deque</strong>, discussed in depth in Chapter 7) have a default allocator argument, the technique shown above is helpful should you ever want to pass one of these sequences as a template parameter. The following program passes a <strong>vector</strong> and then a <strong>list</strong> to two instances of <strong>Container</strong><sup><strong>.</strong></sup></p><p>//: C05:TempTemp4.cpp</p><p>//{-bor}</p><p>//{-msc}</p><p>// Passes standard sequences as template arguments</p><p>#include &lt;iostream&gt;</p><p>#include &lt;list&gt;</p><p>#include &lt;memory&gt;  // Declares allocator&lt;T&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T, template&lt;class U, class = allocator&lt;U&gt; &gt;</p><p>     class Seq&gt;</p><p>class Container {</p><p>  Seq&lt;T&gt; seq; // Default of allocator&lt;T&gt; applied implicitly</p><p>public:</p><p>  void push_back(const T&amp; t) { seq.push_back(t); }</p><p>  typename Seq&lt;T&gt;::iterator begin() { return seq.begin(); }</p><p>  typename Seq&lt;T&gt;::iterator end() { return seq.end(); }</p><p>};</p><empty-line/><p>int main() {</p><p>  // Use a vector</p><p>  Container&lt;int, vector&gt; theData;</p><p>  theData.push_back(1);</p><p>  theData.push_back(2);</p><p>  for(vector&lt;int&gt;::iterator p = theData.begin();</p><p>      p != theData.end(); ++p) {</p><p>    cout &lt;&lt; *p &lt;&lt; endl;</p><p>  }</p><p>  // Use a list</p><p>  Container&lt;int, list&gt; theOtherData;</p><p>  theOtherData.push_back(3);</p><p>  theOtherData.push_back(4);</p><p>  for(list&lt;int&gt;::iterator p2 = theOtherData.begin();</p><p>      p2 != theOtherData.end(); ++p2) {</p><p>    cout &lt;&lt; *p2 &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>In this case we name the first parameter of the inner template <strong>Seq</strong> (with the name <strong>U</strong>), because the allocators in the standard sequences must themselves be parameterized with the same type as the contained objects in the sequence. Also, since the default <strong>allocator</strong> parameter is known, we can omit it in the subsequent references to <strong>Seq&lt;T&gt;</strong>, as we did in the previous program. To fully explain this example, however, we have to discuss the semantics of the <strong>typename</strong> keyword<sup>.</sup></p></section><section><title><p>The typename keyword</p></title><section><p>Consider the following:<sup>.</sup></p><p>//: C05:TypenamedID.cpp</p><p>//{-bor}</p><p>// Uses 'typename' as a prefix for nested types</p><empty-line/><p>template&lt;class T&gt; class X {</p><p>  // Without typename, you should get an error:</p><p>  typename T::id i;</p><p>public:</p><p>  void f() { i.g(); }</p><p>};</p><empty-line/><p>class Y {</p><p>public:</p><p>  class id {</p><p>  public:</p><p>    void g() {}</p><p>  };</p><p>};</p><empty-line/><p>int main() {</p><p>  X&lt;Y&gt; xy;</p><p>  xy.f();</p><p>} ///:~</p><empty-line/><p>The template definition assumes that the class <strong>T</strong> that you hand it must have a nested identifier of some kind called <strong>id</strong>. But <strong>id</strong> could also be a static data member of <strong>T</strong>, in which case you can perform operations on <strong>id </strong>directly, but you can’t "create an object" of "the type <strong>id</strong>."<sup>.</sup></p><p>However, that’s exactly what is happening here: the identifier <strong>id </strong>is being treated as if it were actually a nested type inside <strong>T</strong>. In the case of class <strong>Y</strong>, <strong>id</strong> is in fact a nested type, but (without the <strong>typename </strong>keyword) the compiler can’t know that when it’s compiling <strong>X</strong><sup><strong>.</strong></sup></p><p>If the compiler has the option of treating an identifier as a type or as something other than a type when it sees an identifier in a template, it will assume that the identifier refers to something other than a type. That is, it will assume that the identifier refers to an object (including variables of primitive types), an enumeration, or something similar. However, it will not–cannot–just assume that it is a type<sup>.</sup></p><p>Because the default behavior of the compiler is to assume that a name that fits the above two points is not a type, you must use <strong>typename</strong> for nested names (except in constructor initializer lists, where it is neither needed nor allowed). In the above example, when the compiler sees <strong>template T::id</strong>, it knows (because of the <strong>typename</strong> keyword) that <strong>id</strong> refers to a nested type and thus it can create an object of that type<sup>.</sup></p><p>The short version of the rule is: if a type referred to inside template code is qualified by a template type parameter, it should be preceded by the <strong>typename</strong> keyword, unless it appears in a base class specification or initializer list in the same scope (in which case you must not).</p><p>All the above explains the use of the <strong>typename</strong> keyword in the program <strong>TempTemp4.cpp</strong>. Without it, the compiler would assume that the expression <strong>Seq&lt;T&gt;::iterator</strong> is not a type, but we were using it to define the return type of the <strong>begin( )</strong> and <strong>end( )</strong> member functions<sup>.</sup></p><p>The following example, which defines a function template that can print any standard C++ sequence, shows a similar use of <strong>typename</strong>.</p><p>//: C05:PrintSeq.cpp</p><p>//{-msc}</p><p>// A print function for standard C++ sequences</p><p>#include &lt;iostream&gt;</p><p>#include &lt;list&gt;</p><p>#include &lt;memory&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T, template&lt;class U, class = allocator&lt;U&gt; &gt;</p><p>   class Seq&gt;</p><p>void printSeq(Seq&lt;T&gt;&amp; seq) {</p><p>  for (typename Seq&lt;T&gt;::iterator b = seq.begin();</p><p>       b != seq.end();)</p><p>    cout &lt;&lt; *b++ &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main() {</p><p>  // Process a vector</p><p>  vector&lt;int&gt; v;</p><p>  v.push_back(1);</p><p>  v.push_back(2);</p><p>  printSeq(v);</p><p>  // Process a list</p><p>  list&lt;int&gt; lst;</p><p>  lst.push_back(3);</p><p>  lst.push_back(4);</p><p>  printSeq(lst);</p><p>} ///:~</p><empty-line/><p>Once again, without the <strong>typename</strong> keyword the compiler will interpret <strong>iterator</strong> as a static data member of <strong>Seq&lt;T&gt;</strong>, which is a syntax error, since a type is required<sup>.</sup></p></section><section><section><title><p>Typedef-ing a typename</p></title><p>It’s important not to assume that the <strong>typename</strong> keyword creates a new type name. It doesn’t. Its purpose is to inform the compiler that the qualified identifier is to be interpreted as a type. A line that reads:<sup>.</sup></p><p>typename Seq&lt;T&gt;::iterator It;</p><empty-line/><p>causes a variable named <strong>It</strong> to be declared of type <strong>Seq&lt;T&gt;::iterator</strong>. If you mean to create a new type name, you should use <strong>typedef</strong>, as usual, as in:<sup>.</sup></p><p>typedef typename Seq&lt;It&gt;::iterator It;</p><empty-line/></section><section><title><p>Using typename instead of class</p></title><p>Another role of the <strong>typename</strong> keyword is to provide you the option of using <strong>typename</strong> instead of <strong>class</strong> in the template argument list of a template definition. To some, this produces clearer code (your mileage may vary):<sup>.</sup></p><p>//: C05:UsingTypename.cpp</p><p>// Using 'typename' in the template argument list</p><empty-line/><p>template&lt;typename T&gt; class X { };</p><empty-line/><p>int main() {</p><p>  X&lt;int&gt; x;</p><p>} ///:~</p><empty-line/><p>You probably won’t see a great deal of code that uses <strong>typename</strong> in this fashion, since the keyword was added to the language a relatively long time after templates were introduced<sup>.</sup></p></section></section></section><section><title><p>Using the template keyword as a hint</p></title><p>Just as the <strong>typename</strong> keyword helps the compiler in situations in which a type identifier is not expected, there is also a potential difficulty with tokens that are not identifiers, such as the <strong>&lt;</strong> and <strong>&gt;</strong> characters; sometimes they represent the less-than or greater-than symbols, and sometimes they delimit template parameter lists. As an example, we’ll once more use the <strong>bitset</strong> class:<sup>.</sup></p><p>//: C05:DotTemplate.cpp</p><p>// Illustrate the .template construct</p><p>#include &lt;bitset&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class charT, size_t N&gt;</p><p>basic_string&lt;charT&gt; bitsetToString(const bitset&lt;N&gt;&amp; bs) {</p><p>  return bs. template to_string&lt;charT, char_traits&lt;charT&gt;,</p><p>                                allocator&lt;charT&gt; &gt;();</p><p>}</p><empty-line/><p>int main() {</p><p>  bitset&lt;10&gt; bs;</p><p>  bs.set(1);</p><p>  bs.set(5);</p><p>  cout &lt;&lt; bs &lt;&lt; endl; // 0000100010</p><p>  string s = bitsetToString&lt;char&gt;(bs);</p><p>  cout &lt;&lt; s &lt;&lt; endl;  // 0000100010</p><p>} ///:~</p><empty-line/><p>The <strong>bitset</strong> class supports conversion to string object via its <strong>to_string</strong> member function. To support multiple string classes, <strong>to_string</strong> is itself a template, following the pattern established by the <strong>basic_string</strong> template discussed in Chapter 3. The declaration of <strong>to_string</strong> inside of <strong>bitset</strong> looks like this:<sup>.</sup></p><p>template &lt;class charT, class traits, class Allocator&gt;</p><p>basic_string&lt;charT, traits, Allocator&gt; to_string() const;</p><empty-line/><p>Our <strong>bitsetToString( )</strong> function template above allows you to request different types of string representations of a <strong>bitset</strong>. To get a wide string, for instance, you change the call to the following:</p><p>  wstring s = bitsetToString&lt;wchar_t&gt;(bs);</p><empty-line/><p>Note that <strong>basic_string</strong> uses default template arguments, so we don’t have to repeat the <strong>char_traits</strong> and <strong>allocator</strong> arguments in the return value. Unfortunately, <strong>bitset::to_string</strong> does not use default arguments. Using <strong>bitsetToString&lt;char&gt;( bs)</strong> is more convenient than typing a fully-qualified call to <strong>bs.template to_string&lt;char, char_traits, allocator&lt;char&gt; &gt;( )</strong> every time<sup>.</sup></p><p>The return statement in <strong>bitsetToString( )</strong> contains the <strong>template</strong> keyword in an odd place—right after the dot operator applied to the <strong>bitset</strong> object <strong>bs</strong>. This is because when the template is parsed, the <strong>&lt;</strong> character after the <strong>to_string</strong> token would be interpreted as a less-than operation instead of the beginning or a template argument list. We explain exactly why this confusion exists in the section "Name lookup issues" later in this chapter. The <strong>template</strong> keyword used in this context tells the compiler that what follows is the name of a template, causing the <strong>&lt;</strong> character to be interpreted correctly. The same reasoning applies to the <strong>-&gt;</strong> and <strong>::</strong> operators when applied to templates. As with the <strong>typename</strong> keyword, this template disambiguation technique can only be used within a template.<sup>[50]</sup></p></section><section><title><p>Member Templates</p></title><p>The <strong>bitset::to_string( )</strong> function template is an example of a <emphasis>member template</emphasis>: a template declared within another class or class template. This allows many combinations of independent template arguments to be combined. A useful example is found in the <strong>complex</strong> class template in the standard C+ library. The <strong>complex</strong> template has a type parameter meant to represent an underlying floating-point type to hold the real and imaginary parts of a complex number. The following code snippet from the standard library shows a member-template constructor in the <strong>complex</strong> class template:<sup>.</sup></p><p>template&lt;typename T&gt;</p><p>class complex {</p><p>public:</p><p>  template&lt;class X&gt; complex(const complex&lt;X&gt;&amp;);</p><empty-line/><p>The standard <strong>complex</strong> template comes ready-made with specializations that use <strong>float</strong>, <strong>double</strong>, and <strong>long double</strong> for the parameter <strong>T</strong>. The member-template constructor above allows you to create a new complex number that uses a different floating-point type as its base type, as seen in the code below:<sup>.</sup></p><p>  complex&lt;float&gt; z(1,2);</p><p>  complex&lt;double&gt; w(z);</p><empty-line/><p>In the declaration of <strong>w</strong>, the <strong>complex</strong> template parameter <strong>T</strong> is <strong>double</strong> and <strong>X</strong> is <strong>float</strong>. Member templates make this kind of flexible conversion easy<sup>.</sup></p><p>Since defining a template within a template is a nesting operation, the prefixes that introduce the templates must reflect that nesting if you define the member template outside the outer class definition. For example, if you were to implement the <strong>complex</strong> class template, and if you were to define the member-template constructor above outside the <strong>complex</strong> template class definition, you would have to do it like this:<sup>.</sup></p><p>template&lt;typename T&gt;</p><p>template&lt;typename X&gt;</p><p>complex&lt;T&gt;::complex(const complex&lt;X&gt;&amp; c) {/*body here…*/}</p><empty-line/><p>Another use of member function templates in the standard library is in the initialization of containers, such as a <strong>vector</strong>. Suppose we have a <strong>vector</strong> of <strong>int</strong>s and we want to initialize a new vector of <strong>doubles</strong> with it, like this:<sup>.</sup></p><p>  int data[5] = {1,2,3,4,5};</p><p>  vector&lt;int&gt; v1(data, data+5);</p><p>  vector&lt;double&gt; v2(v1.begin(), v1.end());</p><empty-line/><p>As long as the elements in <strong>v1</strong> are assignment-compatible with the elements in <strong>v2</strong> (as <strong>double</strong> and <strong>int</strong> are here), all is well. The <strong>vector</strong> class template has the following member template constructor:<sup>.</sup></p><p>template &lt;class InputIterator&gt;</p><p>vector(InputIterator first, InputIterator last,</p><p>       const Allocator&amp; = Allocator());</p><empty-line/><p>This constructor is actually used twice in the vector declarations above. When <strong>v1</strong> is initialized from the array of <strong>int</strong>s, the type <strong>InputIterator</strong> is <strong>int*</strong>. When <strong>v2</strong> is initialized from <strong>v1</strong>, an instance of the member template constructor is used with <strong>InputIterator</strong> representing <strong>vector&lt;int&gt;::iterator</strong><sup><strong>.</strong></sup></p><p>Member templates can also be classes. (They don’t have to be functions, although that’s usually what you need.) The following example shows a member class template inside an outer class template<sup>.</sup></p><p>//: C05:MemberClass.cpp</p><p>// A member class template</p><p>#include &lt;iostream&gt;</p><p>#include &lt;typeinfo&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T&gt;</p><p>class Outer {</p><p>public:</p><p>  template&lt;class R&gt;</p><p>  class Inner {</p><p>  public:</p><p>    void f();</p><p>  };</p><p>};</p><empty-line/><p>template&lt;class T&gt; template &lt;class R&gt;</p><p>void Outer&lt;T&gt;::Inner&lt;R&gt;::f() {</p><p>  cout &lt;&lt; "Outer == " &lt;&lt; typeid(T).name() &lt;&lt; endl;</p><p>  cout &lt;&lt; "Inner == " &lt;&lt; typeid(R).name() &lt;&lt; endl;</p><p>  cout &lt;&lt; "Full Inner == " &lt;&lt; typeid(*this).name() &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main() {</p><p>  Outer&lt;int&gt;::Inner&lt;bool&gt; inner;</p><p>  inner.f();</p><p>} ///:~</p><empty-line/><p>The <strong>typeid</strong> operator, which is covered in Chapter 8, returns an object whose <strong>name( )</strong> member function yields a string representation of a type or of the type of a variable. Although the exact representation varies from compiler to compiler, the output of the program above should be something like this:<sup>.</sup></p><p>Outer == int</p><p>Inner == bool</p><p>Full Inner == Outer&lt;int&gt;::Inner&lt;bool&gt;</p><empty-line/><p>The declaration of the variable <strong>inner</strong> in the main program instantiates both <strong>Inner&lt;bool&gt;</strong> and <strong>Outer&lt;int&gt;</strong><sup><strong>.</strong></sup></p><p>Member template functions cannot be declared <strong>virtual</strong>. Current compiler technology expects to be able to fix the size of a class’s virtual function table when the class is parsed. Allowing virtual member template functions would require knowing all calls to such member functions everywhere in the program ahead of time, which is not feasible, especially for multi-file projects<sup>.</sup></p></section></section><section><title><p>Function template issues</p></title><section><p>Just as a class template describes a family of classes, a function template describes a family of functions. The syntax for creating either type of template is virtually identical, but they differ somewhat in how they are used. You must always use angle brackets when instantiating class templates and you must supply all non-default template arguments. With function templates, on the other hand, you can often omit the template arguments, and default template arguments are not even allowed.[ ]Consider a typical implementation of the <strong>min( )</strong> function template declared in the <strong>&lt;algorithm&gt;</strong> header, which looks something like this:<sup>.</sup></p><p>template&lt;typename T&gt;</p><p>const T&amp; min(const T&amp; a, const T&amp; b) {</p><p>  return (a &lt; b) ? a : b;</p><p>}</p><empty-line/><p>You could invoke this template by providing the type of the arguments in angle brackets, just like you do with class templates, as in:</p><p>int z = min&lt;int&gt;(i, j);</p><empty-line/><p>This syntax tells the compiler that a specialization of the <strong>min</strong> template is needed with <strong>int</strong> used in place of the parameter <strong>T</strong>, whereupon the compiler generates the corresponding code. Following the pattern of naming the classes generated from class templates, you can think of the name of the instantiated function as <strong>min&lt;int&gt;</strong><sup><strong>.</strong></sup></p></section><section><title><p>Type deduction of function template arguments</p></title><p>You can always use such explicit function template specification as in the example above, but it is often convenient to leave off the template arguments and let the compiler deduce them from the function arguments, like this:<sup>.</sup></p><p>int z = min(i, j);</p><empty-line/><p>If both <strong>i</strong> and <strong>j</strong> are <strong>int</strong>s, the compiler knows that you need <strong>min&lt;int&gt;</strong>, which it then instantiates automatically. The types must be identical, because the template was originally specified with only one template type argument used for both function parameters. No standard conversions are applied for function arguments whose type is specified by a template parameter. For example, if you wanted to find the minimum of an <strong>int</strong> and a <strong>double</strong>, the following attempt at a call to <strong>min</strong> would fail:<sup>.</sup></p><p>int z = min(x, j); // x is a double</p><empty-line/><p>Since <strong>x</strong> and <strong>j</strong> are distinct types, no single parameter matches the template parameter <strong>T</strong> in the definition of <strong>min;</strong> so the call does not match the template declaration. You can work around this difficulty by casting one argument to the other’s type or by reverting to the fully-specified call syntax, as in:<sup>.</sup></p><p>int z = min&lt;double&gt;(x, j);</p><empty-line/><p>This tells the compiler to generate the <strong>double</strong> version of <strong>min</strong>, after which <strong>j</strong> can be promoted to a <strong>double</strong> by normal standard conversion rules (because the function <strong>min&lt;double&gt;(const double&amp;, const double&amp;)</strong> would then exist)<sup>.</sup></p><p>You might be tempted to require two parameters for <strong>min</strong>, allowing the types of the arguments to be independent, like this:</p><p>template&lt;typename T, typename U&gt;</p><p>const T&amp; min(const T&amp; a, const U&amp; b) {</p><p>  return (a &lt; b) ? a : b;</p><p>}</p><empty-line/><p>This is often a good strategy, but in this case it is problematic because <strong>min</strong> must return a value, and there is no satisfactory way to determine which type it should be (<strong>T</strong> or <strong>U</strong>?)<sup>.</sup></p><p>If the return type of a function template is an independent template parameter, you must always specify its type explicitly when you call it, since there is no argument from which to deduce it. Such is the case with the <strong>fromString</strong> template below<sup>.</sup></p><p>//: C05:StringConv.h</p><p>#ifndef STRINGCONV_H</p><p>#define STRINGCONV_H</p><p>// Function templates to convert to and from strings</p><p>#include &lt;string&gt;</p><p>#include &lt;sstream&gt;</p><empty-line/><p>template&lt;typename T&gt;</p><p>T fromString(const std::string&amp; s) {</p><p>  std::istringstream is(s);</p><p>  T t;</p><p>  is &gt;&gt; t;</p><p>  return t;</p><p>}</p><empty-line/><p>template&lt;typename T&gt;</p><p>std::string toString(const T&amp; t) {</p><p>  std::ostringstream s;</p><p>  s &lt;&lt; t;</p><p>  return s.str();</p><p>}</p><p>#endif // STRINGCONV_H ///:~</p><empty-line/><p>These function templates provide conversions to and from <strong>std:: string</strong> for any types that provide a stream inserter or extractor, respectively. Here’s a test program that includes the use of the standard library <strong>complex</strong> number type:<sup>.</sup></p><p>//: C05:StringConvTest.cpp</p><p>#include "StringConv.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;complex&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  int i = 1234;</p><p>  cout &lt;&lt; "i == \"" &lt;&lt; toString(i) &lt;&lt; "\"\n";</p><p>  float x = 567.89;</p><p>  cout &lt;&lt; "x == \"" &lt;&lt; toString(x) &lt;&lt; "\"\n";</p><p>  complex&lt;float&gt; c(1.0, 2.0);</p><p>  cout &lt;&lt; "c == \"" &lt;&lt; toString(c) &lt;&lt; "\"\n";</p><p>  cout &lt;&lt; endl;</p><empty-line/><p>  i = fromString&lt;int&gt;(string("1234"));</p><p>  cout &lt;&lt; "i == " &lt;&lt; i &lt;&lt; endl;</p><p>  x = fromString&lt;float&gt;(string("567.89"));</p><p>  cout &lt;&lt; "x == " &lt;&lt; x &lt;&lt; endl;</p><p>  c = fromString&lt; complex&lt;float&gt; &gt;(string("(1.0,2.0)"));</p><p>  cout &lt;&lt; "c == " &lt;&lt; c &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The output is what you’d expect:<sup>.</sup></p><p>i == "1234"</p><p>x == "567.89"</p><p>c == "(1,2)"</p><empty-line/><p>i == 1234</p><p>x == 567.89</p><p>c == (1,2)</p><empty-line/><p>Notice that in each of the instantiations of <strong>fromString</strong>, the template parameter is specified in the call. If you have a function template with template parameters for the parameter types as well as the return types, it is important to declare the return type parameter first; otherwise you won’t be able to omit the type parameters for the function parameters. As an illustration, consider the following well-known function template:<sup>[51]</sup></p><p>//: C05:ImplicitCast.cpp</p><p>template&lt;typename R, typename P&gt;</p><p>R implicit_cast(const P&amp; p) {</p><p>  return p;</p><p>}</p><empty-line/><p>int main() {</p><p>  int i = 1;</p><p>  float x = implicit_cast&lt;float&gt;(i);</p><p>  int j = implicit_cast&lt;int&gt;(x);</p><p>  // char* p = implicit_cast&lt;char*&gt;(i);</p><p>} ///:~</p><empty-line/><p>If you interchange <strong>R</strong> and <strong>P</strong> in the template parameter list near the top of the file, it will be impossible to compile this program because the return type will remain unspecified (since the first template parameter would be the function’s parameter type). The last line (which is commented out) is illegal because there is no standard conversion from <strong>int</strong> to <strong>char*</strong>; <strong>implicit_cast</strong> is for revealing in your code conversions that are allowed naturally<sup>.</sup></p><p>With a little care you can even deduce array dimensions. The following example has an array-initialization function template (<strong>init2</strong>) that does just that.</p><p>//: C05:ArraySize.cpp</p><p>#include &lt;cstddef&gt;</p><p>using std::size_t;</p><empty-line/><p>template&lt;size_t R, size_t C, typename T&gt;</p><p>void init1(T a[R][C]) {</p><p>  for (size_t i = 0; i &lt; R; ++i)</p><p>    for (size_t j = 0; j &lt; C; ++j)</p><p>      a[i][j] = T();</p><p>}</p><empty-line/><p>template&lt;size_t R, size_t C, class T&gt;</p><p>void init2(T (&amp;a)[R][C]) {  // reference parameter</p><p>  for (size_t i = 0; i &lt; R; ++i)</p><p>    for (size_t j = 0; j &lt; C; ++j)</p><p>      a[i][j] = T();</p><p>}</p><empty-line/><p>int main() {</p><p>  int a[10][20];</p><p>  init1&lt;10,20&gt;(a);  // must specify</p><p>  init2(a);         // sizes deduced</p><p>} ///:~</p><empty-line/><p>Array dimensions are not passed as part of a function parameter’s type unless that parameter is passed by pointer or reference. The function template <strong>init2</strong> declares <strong>a</strong> to be a reference to a two-dimensional array, so its dimensions <strong>R</strong> and <strong>C</strong> are deduced by the template facility, making <strong>init2</strong> a handy way to initialize a two-dimensional array of any size. The template <strong>init1</strong> does not pass the array by reference, so the sizes must be explicitly specified, although the type parameter can still deduced<sup>.</sup></p></section><section><title><p>Function template overloading</p></title><p>As with functions, you can overload function templates that have the same name. When the compiler processes a function call in a program, it has to decide which template or ordinary function is the "best" fit for the call. Assuming the existence of the <strong>min</strong> function template introduced earlier, let’s add some ordinary functions to the mix:<sup>.</sup></p><p>//: C05:MinTest.cpp</p><p>#include &lt;cstring&gt;</p><p>#include &lt;iostream&gt;</p><p>using std::strcmp;</p><p>using std::cout;</p><p>using std::endl;</p><empty-line/><p>template&lt;typename T&gt; const T&amp; min(const T&amp; a, const T&amp; b) {</p><p>  return (a &lt; b) ? a : b;</p><p>}</p><p>const char* min(const char* a, const char* b) {</p><p>  return (strcmp(a, b) &lt; 0) ? a : b;</p><p>}</p><p>double min(double x, double y) {</p><p>  return (x &lt; y) ? x : y;</p><p>}</p><empty-line/><p>int main() {</p><p>  const char *s2 = "say \"Ni-!\"", *s1 = "knights who";</p><p>  cout &lt;&lt; min(1, 2) &lt;&lt; endl;      // 1: 1 (template)</p><p>  cout &lt;&lt; min(1.0, 2.0) &lt;&lt; endl;  // 2: 1 (double)</p><p>  cout &lt;&lt; min(1, 2.0) &lt;&lt; endl;    // 3: 1 (double)</p><p>  cout &lt;&lt; min(s1, s2) &lt;&lt; endl;    // 4: knights who (const</p><p>                   //  char*)</p><p>  cout &lt;&lt; min&lt;&gt;(s1, s2) &lt;&lt; endl;  // 5: say "Ni-!"</p><p>                   //    (template)</p><p>} ///:~</p><empty-line/><p>In addition to the function template, this program defines two non-template functions: a C-style string version of <strong>min</strong> and a <strong>double</strong> version. If the template doesn’t exist at all, the call in line 1 above have invokes the <strong>double</strong> version of <strong>min</strong> because of the standard conversion from <strong>int</strong> to <strong>double</strong>. Since the template can generate an <strong>int</strong> version, however, that is considered a better match (of course!); so that’s what happens. The call in line 2 is an exact match for the <strong>double</strong> version, of course, and the call in line 3 also invokes the same function, implicitly converting 1 to 1.0. In line 4 the <strong>const char*</strong> version of <strong>min</strong> is called directly. In line 5 we force the compiler to use the template facility by appending empty angle brackets to the function name, whereupon it generates a <strong>const char*</strong> version from the template and uses it (which is verified by the wrong answer—it’s just comparing addresses!<sup>[52]</sup>). If you’re wondering why we used <strong>using</strong> declarations in lieu of the <strong>using namespace std;</strong> directive, some compilers include headers behind the scenes that bring in <strong>std::min</strong>, which would conflict with our declarations of the name <strong>min</strong><sup><strong>.</strong></sup></p><p>As stated above, you can overload templates of the same name, as long as they can be distinguished by the compiler. You could, for example, declare a <strong>min</strong> function template that processes three arguments:</p><p>template&lt;typename T&gt;</p><p>const T&amp; min(const T&amp; a, const T&amp; b, const T&amp; c);</p><empty-line/><p>Versions of this template will be generated only for calls to <strong>min( )</strong> that have three arguments of the same type<sup>.</sup></p></section><section><title><p>Taking the address of a generated function template</p></title><p>In a number of situations you need to take the address of a function. For example, you may have a function that takes an argument of a pointer to another function. Of course, it’s possible that this other function might be generated from a template function, so you need some way to take that kind of address:<sup>[53]</sup></p><p>//: C05:TemplateFunctionAddress.cpp</p><p>// Taking the address of a function generated</p><p>// from a template.</p><empty-line/><p>template &lt;typename T&gt; void f(T*) {}</p><empty-line/><p>void h(void (*pf)(int*)) {}</p><empty-line/><p>template &lt;typename T&gt;</p><p>  void g(void (*pf)(T*)) {}</p><empty-line/><p>int main() {</p><p>  // Full type specification:</p><p>  h(&amp;f&lt;int&gt;);</p><p>  // Type deduction:</p><p>  h(&amp;f);</p><p>  // Full type specification:</p><p>  g&lt;int&gt;(&amp;f&lt;int&gt;);</p><p>  // Type deduction:</p><p>  g(&amp;f&lt;int&gt;);</p><p>  // Partial (but sufficient) specification</p><p>  g&lt;int&gt;(&amp;f);</p><p>} ///:~</p><empty-line/><p>This example demonstrates a number of issues. First, even though you’re using templates, the signatures must match. The function <strong>h( )</strong> takes a pointer to a function that takes an <strong>int*</strong> and returns <strong>void</strong>, and that’s what the template <strong>f</strong> produces. Second, the function that wants the function pointer as an argument can itself be a template, as in the case of the template <strong>g</strong><sup><strong>.</strong></sup></p><p>In <strong>main( )</strong> you can see that type deduction works here too. The first call to <strong>h( )</strong> explicitly gives the template argument for <strong>f</strong>, but since <strong>h( )</strong> says that it will only take the address of a function that takes an <strong>int*</strong>, that part can be deduced by the compiler. With <strong>g( )</strong> the situation is even more interesting because two templates are involved. The compiler cannot deduce the type with nothing to go on, but if either <strong>f</strong> or <strong>g</strong> is given <strong>int</strong>, the rest can be deduced<sup>.</sup></p><p>An obscure issue arises when trying to pass the functions <strong>tolower</strong> or <strong>toupper</strong>, declared in <strong>&lt;cctype&gt;</strong>, as parameters. It is possible to use these in conjunction with the <strong>transform</strong> algorithm (which is covered in detail in the next chapter), for example, to convert a string to lower or upper case. Care must be taken, however, because there are multiple declarations for these functions. A na&#xEF;ve approach would is something like this:<sup>.</sup></p><p>// The variable <strong>s</strong> is a std::string</p><p>transform(s.begin(), s.end(), s.begin(), tolower);</p><empty-line/><p>The <strong>transform</strong> algorithm applies its fourth parameter (<strong>tolower</strong> in this case) to each character in the string <strong>s</strong> and places the result in <strong>s</strong> itself, thus overwriting each character in <strong>s</strong> with its lower-case equivalent. As it is written, this statement may or may not work! It fails in the following context:<sup>.</sup></p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cctype&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  string s("LOWER");</p><p>  transform(s.begin(),s.end(),s.begin(),tolower);</p><p>  cout &lt;&lt; s &lt;&lt; endl;</p><p>}</p><empty-line/><p>Even if your compiler let’s you get away with this, it is illegal. The reason is that the <strong>&lt;iostream&gt;</strong> header also makes available a two-argument version of <strong>tolower</strong> and <strong>toupper</strong>:</p><p>template &lt;class charT&gt; charT toupper(charT c,</p><p>                      const locale&amp; loc);</p><p>template &lt;class charT&gt; charT tolower(charT c,</p><p>                      const locale&amp; loc);</p><empty-line/><p>These function templates take a second argument of type <strong>locale</strong>. The compiler has no way of knowing whether it should use the one-argument version of <strong>tolower</strong> defined in <strong>&lt;cctype&gt;</strong> or the one mentioned above. You can solve this problem (almost!) with a cast in the call to <strong>transform</strong>, as follows:<sup>.</sup></p><p>  transform(s.begin(),s.end(),s.begin()</p><p>            static_cast&lt;int (*)(int)&gt;(tolower));</p><empty-line/><p>(Recall that <strong>tolower</strong> and <strong>toupper</strong> traffic in <strong>int</strong> instead of <strong>char</strong>.) The cast above makes clear that the single-argument version of <strong>tolower</strong> is desired. Once again, this works with some compilers, but it is not required to. The reason, albeit obscure, is that a library implementation is allowed to give "C linkage" (meaning that the function name does not contain all the auxiliary information<sup>[54]</sup> that normal C++ functions do) to functions inherited from the C language. If this is the case, the cast fails, because <strong>transform</strong> is a C++ function template and expects its fourth argument to have C++ linkage—and a cast is not allowed to change the linkage. What a predicament!<sup>.</sup></p><p>The solution is to place calls to <strong>tolower</strong> in an unambiguous context. For example, you could write a function, let’s call it <strong>strTolower( )</strong>, and place it in its own file without including <strong>&lt;iostream&gt;</strong>, like this:<sup>.</sup></p><p>//: C05:StrTolower.cpp {O}</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cctype&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>string strTolower(string s) {</p><p>  transform(s.begin(), s.end(), s.begin(), tolower);</p><p>  return s;</p><p>} ///:~</p><empty-line/><p>The header <strong>&lt;iostream&gt;</strong> is not involved here, and the compilers we use do not introduce the two-argument version of <strong>tolower</strong> in this context,<sup>[55]</sup> so there’s no problem. You can then use this function normally:<sup>.</sup></p><p>//: C05:Tolower.cpp</p><p>//{L} StrTolower</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cctype&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><p>string strTolower(string);</p><empty-line/><p>int main() {</p><p>  string s("LOWER");</p><p>  cout &lt;&lt; strTolower(s) &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>Another solution is to write a wrapper function template that calls the correct version of <strong>tolower</strong> explicitly:</p><p>//: C05:ToLower2.cpp</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cctype&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class charT&gt;</p><p>charT strTolower(charT c) {</p><p>  return tolower(c);  // one-arg version called</p><p>}</p><empty-line/><p>int main() {</p><p>  string s("LOWER");</p><p>  transform(s.begin(),s.end(),s.begin(),&amp;strTolower&lt;char&gt;);</p><p>  cout &lt;&lt; s &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>This version has the advantage that it can process both wide and narrow strings since the underlying character type is a template parameter. The C++ standards committee is working on modifying the language so that the first example (without the cast) will work, and some day these workarounds can be ignored.<sup>[56]</sup></p></section><section><title><p>Applying a function to an STL sequence</p></title><p>Suppose you want to take an STL sequence container (which you’ll learn more about in subsequent chapters; for now we can just use the familiar <strong>vector</strong>) and apply a function to all the objects it contains. Because a <strong>vector</strong> can contain any type of object, you need a function that works with any type of <strong>vector</strong>:<sup>.</sup></p><p>//: C05:ApplySequence.h</p><p>// Apply a function to an STL sequence container</p><empty-line/><p>// 0 arguments, any type of return value:</p><p>template&lt;class Seq, class T, class R&gt;</p><p>void apply(Seq&amp; sq, R (T::*f)()) {</p><p>  typename Seq::iterator it = sq.begin();</p><p>  while(it != sq.end()) {</p><p>    ((*it)-&gt;*f)();</p><p>    it++;</p><p>  }</p><p>}</p><empty-line/><p>// 1 argument, any type of return value:</p><p>template&lt;class Seq, class T, class R, class A&gt;</p><p>void apply(Seq&amp; sq, R(T::*f)(A), A a) {</p><p>  typename Seq::iterator it = sq.begin();</p><p>  while(it != sq.end()) {</p><p>    ((*it)-&gt;*f)(a);</p><p>    it++;</p><p>  }</p><p>}</p><empty-line/><p>// 2 arguments, any type of return value:</p><p>template&lt;class Seq, class T, class R,</p><p>         class A1, class A2&gt;</p><p>void apply(Seq&amp; sq, R(T::*f)(A1, A2),</p><p>    A1 a1, A2 a2) {</p><p>  typename Seq::iterator it = sq.begin();</p><p>  while(it != sq.end()) {</p><p>    ((*it)-&gt;*f)(a1, a2);</p><p>    it++;</p><p>  }</p><p>}</p><p>// Etc., to handle maximum likely arguments ///:~</p><empty-line/><p>The <strong>apply( ) </strong>function template takes a reference to the container class and a pointer-to-member for a member function of the objects contained in the class. It uses an iterator to move through the <strong>Stack</strong> and apply the function to every object<sup>.</sup></p><p>Notice that there are no STL header files (or any header files, for that matter) included in <strong>applySequence.h</strong>, so it is actually not limited to use with an STL container. However, it does make assumptions (primarily, the name and behavior of the <strong>iterator</strong>) that apply to STL sequences<sup>.</sup></p><p>You can see there is more than one version of <strong>apply( )</strong>, further illustrating overloading of function templates. Although these templates allow any type of return value (which is ignored, but the type information is required to match the pointer-to-member), each version takes a different number of arguments, and because it’s a template, those arguments can be of any type. The only limitation here is that there’s no "super template" to create templates for you; you must decide how many arguments will ever be required<sup>.</sup></p><p>To test the various overloaded versions of <strong>apply( )</strong>, the class <strong>Gromit</strong><sup>[57]</sup> is created containing functions with different numbers of arguments:<sup>.</sup></p><p>//: C05:Gromit.h</p><p>// The techno-dog. Has member functions</p><p>// with various numbers of arguments.</p><p>#include &lt;iostream&gt;</p><empty-line/><p>class Gromit {</p><p>  int arf;</p><p>public:</p><p>  Gromit(int arf = 1) : arf(arf + 1) {}</p><p>  void speak(int) {</p><p>    for(int i = 0; i &lt; arf; i++)</p><p>      std::cout &lt;&lt; "arf! ";</p><p>    std::cout &lt;&lt; std::endl;</p><p>  }</p><p>  char eat(float) {</p><p>    std::cout &lt;&lt; "chomp!" &lt;&lt; std::endl;</p><p>    return 'z';</p><p>  }</p><p>  int sleep(char, double) {</p><p>    std::cout &lt;&lt; "zzz..." &lt;&lt; std::endl;</p><p>    return 0;</p><p>  }</p><p>  void sit() {</p><p>    std::cout &lt;&lt; " Sitting...)" &lt;&lt; std::endl;</p><p>  }</p><p>}; ///:~</p><empty-line/><p>Now you can use the <strong>apply( )</strong> template functions to apply the <strong>Gromit</strong> member functions to a <strong>vector&lt;Gromit*&gt;,</strong> like this:<sup>.</sup></p><p>//: C05:ApplyGromit.cpp</p><p>// Test ApplySequence.h</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;vector&gt;</p><p>#include "ApplySequence.h"</p><p>#include "Gromit.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  vector&lt;Gromit*&gt; dogs;</p><p>  for(size_t i = 0; i &lt; 5; i++)</p><p>    dogs.push_back(new Gromit(i));</p><p>  apply(dogs, &amp;Gromit::speak, 1);</p><p>  apply(dogs, &amp;Gromit::eat, 2.0f);</p><p>  apply(dogs, &amp;Gromit::sleep, 'z', 3.0);</p><p>  apply(dogs, &amp;Gromit::sit);</p><p>  for (size_t i = 0; i &lt; dogs.size(); ++i)</p><p>    delete dogs[i];</p><p>} ///:~</p><empty-line/><p>Although the definition of <strong>apply( )</strong> is somewhat complex and not something you’d ever expect a novice to understand, its use is remarkably clean and simple, and a novice could easily use it knowing only <emphasis>what</emphasis> it is intended to accomplish, not <emphasis>how</emphasis>. This is the type of division you should strive for in all your program components: The tough details are all isolated on the designer’s side of the wall. Users are concerned only with accomplishing their goals and don’t see, know about, or depend on details of the underlying implementation. We’ll explore even more flexible ways to apply functions to sequences in the next chapter<sup>.</sup></p></section><section><title><p>Partial ordering of function templates</p></title><p>We mentioned earlier that an ordinary function overload of <strong>min( )</strong> is preferable to using the template. If a function already exists to match a function call, why generate another? In the absence of ordinary functions, however, it is possible that overloaded function templates can lead to ambiguities. To minimize the chances of this, an ordering is defined for function templates that chooses the <emphasis>most specialized</emphasis> template, if such exists. A function template is considered more specialized than another if every possible list of arguments that matches it also matches the other, but not the other way around. Consider the following function template declarations, taken from an example in the C++ standard document:<sup>.</sup></p><p>template&lt;class T&gt; void f(T);</p><p>template&lt;class T&gt; void f(T*);</p><p>template&lt;class T&gt; void f(const T*);</p><empty-line/><p>The first template can be matched with any type. The second template is more specialized than the first because only pointer types match it. In other words, you can look upon the set of possible calls that match the second template as a subset of the first. A similar relationship exists between the second and third template declarations above: the third can only be called for pointers to <strong>const</strong>, but the second accommodates any pointer type. The following program illustrates these rules<sup>.</sup></p><p>//: C05:PartialOrder.cpp</p><p>// Reveals Ordering of Function Templates</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T&gt;</p><p>void f(T) {</p><p>  cout &lt;&lt; "T\n";</p><p>}</p><empty-line/><p>template&lt;class T&gt;</p><p>void f(T*) {</p><p>  cout &lt;&lt; "T*\n";</p><p>}</p><empty-line/><p>template&lt;class T&gt;</p><p>void f(const T*) {</p><p>  cout &lt;&lt; "const T*\n";</p><p>}</p><empty-line/><p>int main() {</p><p>  f(0);            // T</p><p>  int i = 0;</p><p>  f(&amp;i);           // T*</p><p>  const int j = 0;</p><p>  f(&amp;j);           // const T*</p><p>} ///:~</p><empty-line/><p>The call <strong>f(&amp;i)</strong> certainly matches the first template, but since the second is more specialized, it is called. The third can’t be called in this case since the pointer is not a pointer to <strong>const</strong>. The call <strong>f(&amp;j)</strong> matches all three templates (for example, <strong>T</strong> would be <strong>const int</strong> in the second template), but again, the third template is more specialized, so it is used instead<sup>.</sup></p><p>If there is no "most specialized" template among a set of overloaded function templates, an ambiguity remains and the compiler will report an error. That is why this feature is called a "partial ordering"—it may not be able to resolve all possibilities. Similar rules exist for class templates (see the section "Partial specialization" below)<sup>.</sup></p></section></section><section><title><p>Template specialization</p></title><section><p>The term <emphasis>specialization</emphasis> has a specific, template-related meaning in C++. A template definition is, by its very nature, a <emphasis>generalization</emphasis>, because it describes a family of functions or classes in general terms. When template arguments are supplied, the result is a specialization of the template, because it fixes a unique instance out of the many possible instances of the family of functions or classes. The <strong>min</strong> function template seen at the beginning of this chapter is a generalization of a minimum-finding function, because the type of its parameters is not specified. When you supply the type for the template parameter, whether explicitly or implicitly via argument deduction, the resultant code generated by the compiler (for example, <strong>min&lt;int&gt;</strong>) is a specialization of the template. The code generated is also considered an <emphasis>instantiation</emphasis> of the template, of course, as are all code bodies generated by the template facility<sup>.</sup></p></section><section><title><p>Explicit specialization</p></title><p>You can also provide the code yourself for a given template specialization, should the need arise. Providing your own template specializations is often needed with class templates, but we will begin with the <strong>min</strong> function template to introduce the syntax<sup>.</sup></p><p>Recall that in <strong>MinTest.cpp</strong> earlier in this chapter we introduced the following ordinary function:</p><p>const char* min(const char* a, const char* b) {</p><p>  return (strcmp(a, b) &lt; 0) ? a : b;</p><p>}</p><empty-line/><p>This was so that a call to <strong>min</strong> would compare strings and not addresses. Although it would provide no advantage in this case, we could define instead a <strong>const char*</strong> specialization for <strong>min</strong>, as in the following program:<sup>.</sup></p><p>//: C05:MinTest2.cpp</p><p>#include &lt;cstring&gt;</p><p>#include &lt;iostream&gt;</p><p>using std::strcmp;</p><p>using std::cout;</p><p>using std::endl;</p><empty-line/><p>template&lt;class T&gt; const T&amp; min(const T&amp; a, const T&amp; b) {</p><p>  return (a &lt; b) ? a : b;</p><p>}</p><p>// An explicit specialization of the min template</p><p>template&lt;&gt;</p><p>const char* const&amp; min&lt;const char*&gt;(const char* const&amp; a,</p><p>                     const char* const&amp; b) {</p><p>  return (strcmp(a, b) &lt; 0) ? a : b;</p><p>}</p><empty-line/><p>int main() {</p><p>  const char *s2 = "say \"Ni-!\"", *s1 = "knights who";</p><p>  cout &lt;&lt; min(s1, s2) &lt;&lt; endl;</p><p>  cout &lt;&lt; min&lt;&gt;(s1, s2) &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The "<strong>template&lt;&gt;</strong>" prefix tells the compiler that what follows is a specialization of a template. The type for the specialization must appear in angle brackets immediately following the function name, as it normally would in an explicitly-specified call. Note that we <emphasis>carefully</emphasis> substitute <strong>const char*</strong> for <strong>T</strong> in the explicit specialization. Whenever the original template specifies <strong>const T</strong>, that <strong>const</strong> modifies the <emphasis>whole</emphasis> type <strong>T</strong>. It is the pointer to a <strong>const char*</strong> that is <strong>const</strong>. Therefore we must write <strong>const char* const</strong> in place of <strong>const T</strong> in the specialization. When the compiler sees a call to <strong>min</strong> with <strong>const char*</strong> arguments in the program, it will instantiate our <strong>const char*</strong> version of <strong>min</strong> so it can be called. The two calls to <strong>min</strong> in this program call the same specialization of <strong>min</strong><sup><strong>.</strong></sup></p><p>Explicit specializations tend to be more useful for class templates than for function templates. When you provide a full specialization for a class template, though, you may need to implement all the member functions. This is because you are providing a separate class, and client code may expect the complete interface to be implemented<sup>.</sup></p><p>The standard library has an explicit specialization for <strong>vector</strong> when it is used to hold objects of type <strong>bool</strong>. As you saw earlier in this chapter, the declaration for the primary <strong>vector</strong> class template is:</p><p>template &lt;class T, class Allocator = allocator&lt;T&gt; &gt;</p><p>class vector {…};</p><empty-line/><p>To specialize for objects of type <strong>bool</strong>, you could declare an explicit specialization as follows:</p><p>template &lt;&gt;</p><p>class vector&lt; bool, allocator&lt;bool&gt; &gt; {…};</p><empty-line/><p>Again, this is quickly recognized as a full, explicit specialization because of the <strong>template&lt;&gt;</strong> prefix and because all the primary template’s parameters are satisfied by the argument list appended to the class name. The purpose for <strong>vector&lt;bool&gt;</strong> is to allow library implementations to save space by packing bits into integers.<sup>[58]</sup></p><p>It turns out that <strong>vector&lt;bool&gt;</strong> is a little more flexible than we have described, as seen in the next section.</p></section><section><title><p>Partial Specialization</p></title><section><p>Class templates can also be partially specialized, meaning that at least one of the template parameters is left "open" in some way in the specialization. This is actually what <strong>vector&lt;bool&gt;</strong> does; it specifies the object type (<strong>bool</strong>), but leaves the allocator type unspecified. Here is the actual declaration of <strong>vector&lt;bool&gt;</strong>:</p><p>template &lt;class Allocator&gt;</p><p>class vector&lt;bool, Allocator&gt;;</p><empty-line/><p>You can recognize a partial specialization because non-empty parameter lists appear in angle brackets both after the template keyword (the unspecified parameters) and after the class (the specified arguments). Because of the way <strong>vector&lt;bool&gt;</strong> is defined, a user can provide a custom allocator type, even though the contained type of <strong>bool</strong> is fixed. In other words, specialization, and partial specialization in particular, constitute a sort of "overloading" for class templates<sup>.</sup></p></section><section><section><title><p>Partial ordering of class templates</p></title><p>The rules that determine which template is selected for instantiation are similar to the partial ordering for function templates—the "most specialized" template is selected. An illustration follows. (The string in each <strong>f( )</strong> member function below explains the role of each template definition.)<sup>.</sup></p><p>//: C05:PartialOrder2.cpp</p><p>// Reveals partial ordering of class templates</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T, class U&gt; class C {</p><p>public:</p><p>  void f() {</p><p>    cout &lt;&lt; "Primary Template\n";</p><p>  }</p><p>};</p><empty-line/><p>template&lt;class U&gt; class C&lt;int, U&gt; {</p><p>public:</p><p>  void f() {</p><p>    cout &lt;&lt; "T == int\n";</p><p>  }</p><p>};</p><empty-line/><p>template&lt;class T&gt; class C&lt;T, double&gt; {</p><p>public:</p><p>  void f() {</p><p>    cout &lt;&lt; "U == double\n";</p><p>  }</p><p>};</p><empty-line/><p>template&lt;class T, class U&gt; class C&lt;T*, U&gt; {</p><p>public:</p><p>  void f() {</p><p>    cout &lt;&lt; "T* used \n";</p><p>  }</p><p>};</p><empty-line/><p>template&lt;class T, class U&gt; class C&lt;T, U*&gt; {</p><p>public:</p><p>  void f() {</p><p>    cout &lt;&lt; "U* used\n";</p><p>  }</p><p>};</p><empty-line/><p>template&lt;class T, class U&gt; class C&lt;T*, U*&gt; {</p><p>public:</p><p>  void f() {</p><p>    cout &lt;&lt; "T* and U* used\n";</p><p>  }</p><p>};</p><empty-line/><p>template&lt;class T&gt; class C&lt;T, T&gt; {</p><p>public:</p><p>  void f() {</p><p>    cout &lt;&lt; "T == U\n";</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  C&lt;float, int&gt;().f();    // 1: Primary template</p><p>  C&lt;int, float&gt;().f();    // 2: T == int</p><p>  C&lt;float, double&gt;().f(); // 3: U == double</p><p>  C&lt;float, float&gt;().f();  // 4: T == U</p><p>  C&lt;float*, float&gt;().f(); // 5: T* used [T is float]</p><p>  C&lt;float, float*&gt;().f(); // 6: U* used [U is float]</p><p>  C&lt;float*, int*&gt;().f();  // 7: T* and U* used [float,int]</p><empty-line/><p>  // The following are ambiguous:</p><p>//   8: C&lt;int, int&gt;().f();</p><p>//   9: C&lt;double, double&gt;().f();</p><p>//  10: C&lt;float*, float*&gt;().f();</p><p>//  11: C&lt;int, int*&gt;().f();</p><p>//  12: C&lt;int*, int*&gt;().f();</p><p>} ///:~</p><empty-line/><p>As you can see, you can partially specify template parameters according to whether they are pointer types, or whether they are equal. When the <strong>T*</strong> specialization is used, such as is the case in line 5, <strong>T</strong> itself is not the top-level pointer type that was passed—it is the type that the pointer refers to (<strong>float</strong>, in this case). The <strong>T*</strong> specification is a pattern to allow matching against pointer types. If you were to use <strong>int**</strong> as the first template argument, <strong>T</strong> would be <strong>int*</strong>. Line 8 is ambiguous because having the first parameter as an <strong>int</strong> vs. having the two parameters equal are independent issues—one is not more specialized than the other. Similar logic applies to lines 9 through 12<sup>.</sup></p></section></section></section><section><title><p>A practical example</p></title><p>You can easily derive from a class template, and you can create a new template that instantiates and inherits from an existing template. If the <strong>vector </strong>template does most everything you want, for example, but in a certain application you’d also like a version that can sort itself, you can easily reuse the <strong>vector</strong> code. The following example derives from <strong>vector&lt;T&gt;</strong> and adds sorting<sup>.</sup></p><p>//: C05:Sorted.h</p><p>// Template specialization</p><p>#ifndef SORTED_H</p><p>#define SORTED_H</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><empty-line/><p>template&lt;class T&gt;</p><p>class Sorted : public std::vector&lt;T&gt; {</p><p>public:</p><p>  void sort();</p><p>};</p><empty-line/><p>template&lt;class T&gt;</p><p>void Sorted&lt;T&gt;::sort() { // A simple sort</p><p>  for(int i = size(); i &gt; 0; i--)</p><p>    for(int j = 1; j &lt; i; j++)</p><p>      if(at(j-1) &gt; at(j)) {</p><p>        T t = at(j-1);</p><p>        at(j-1) = at(j);</p><p>        at(j) = t;</p><p>      }</p><p>}</p><empty-line/><p>// Partial specialization for pointers:</p><p>template&lt;class T&gt;</p><p>class Sorted&lt;T*&gt; : public std::vector&lt;T*&gt; {</p><p>public:</p><p>  void sort();</p><p>};</p><empty-line/><p>template&lt;class T&gt;</p><p>void Sorted&lt;T*&gt;::sort() {</p><p>  for(int i = size(); i &gt; 0; i--)</p><p>    for(int j = 1; j &lt; i; j++)</p><p>      if(*at(j-1) &gt; *at(j)) {</p><p>        T* t = at(j-1);</p><p>        at(j-1) = at(j);</p><p>        at(j) = t;</p><p>      }</p><p>}</p><empty-line/><p>// Full specialization for char*</p><p>// (Made inline here for convenience –</p><p>//  normally would place function body in separate file</p><p>//  and only leave declaration here)</p><p>template&lt;&gt;</p><p>inline void Sorted&lt;char*&gt;::sort() {</p><p>  for(int i = size(); i &gt; 0; i--)</p><p>    for(int j = 1; j &lt; i; j++)</p><p>      if(std::strcmp(at(j-1), at(j)) &gt; 0) {</p><p>        char* t = at(j-1);</p><p>        at(j-1) = at(j);</p><p>        at(j) = t;</p><p>      }</p><p>}</p><p>#endif // SORTED_H ///:~</p><empty-line/><p>The <strong>Sorted</strong> template imposes a restriction on all but one of the classes for which it is instantiated: they must contain a <strong>&gt;</strong> operator. It works correctly only with non-pointer objects (including objects of built-in types). The full specialization compares the elements using <strong>strcmp( )</strong> to sort vectors of <strong>char*</strong> according to the null-terminated strings to which they refer<sup>.</sup></p><p>Here’s a driver for <strong>Sorted.h</strong> that uses the randomizer introduced earlier in the chapter:<sup>.</sup></p><p>//: C05:Sorted.cpp</p><p>//{bor} (because of bitset in Urand.h)</p><p>// Testing template specialization</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "Sorted.h"</p><p>#include "Urand.h"</p><p>using namespace std;</p><empty-line/><p>#define asz(a) (sizeof a / sizeof a[0])</p><empty-line/><p>char* words[] = {</p><p>  "is", "running", "big", "dog", "a",</p><p>};</p><p>char* words2[] = {</p><p>  "this", "that", "theother",</p><p>};</p><empty-line/><p>int main() {</p><p>  Sorted&lt;int&gt; is;</p><p>  Urand&lt;47&gt; rand;</p><p>  for(size_t i = 0; i &lt; 15; i++)</p><p>    is.push_back(rand());</p><p>  for(size_t i = 0; i &lt; is.size(); i++)</p><p>    cout &lt;&lt; is[i] &lt;&lt; ' ';</p><p>  cout &lt;&lt; endl;</p><p>  is.sort();</p><p>  for(size_t i = 0; i &lt; is.size(); i++)</p><p>    cout &lt;&lt; is[i] &lt;&lt; ' ';</p><p>  cout &lt;&lt; endl;</p><empty-line/><p>  // Uses the template partial specialization:</p><p>  Sorted&lt;string*&gt; ss;</p><p>  for(size_t i = 0; i &lt; asz(words); i++)</p><p>    ss.push_back(new string(words[i]));</p><p>  for(size_t i = 0; i &lt; ss.size(); i++)</p><p>    cout &lt;&lt; *ss[i] &lt;&lt; ' ';</p><p>  cout &lt;&lt; endl;</p><p>  ss.sort();</p><p>  for(size_t i = 0; i &lt; ss.size(); i++) {</p><p>    cout &lt;&lt; *ss[i] &lt;&lt; ' ';</p><p>    delete ss[i];</p><p>  }</p><p>  cout &lt;&lt; endl;</p><empty-line/><p>  // Uses the full char* specialization:</p><p>  Sorted&lt;char*&gt; scp;</p><p>  for(size_t i = 0; i &lt; asz(words2); i++)</p><p>    scp.push_back(words2[i]);</p><p>  for(size_t i = 0; i &lt; scp.size(); i++)</p><p>    cout &lt;&lt; scp[i] &lt;&lt; ' ';</p><p>  cout &lt;&lt; endl;</p><p>  scp.sort();</p><p>  for(size_t i = 0; i &lt; scp.size(); i++)</p><p>    cout &lt;&lt; scp[i] &lt;&lt; ' ';</p><p>  cout &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>Each of the template instantiations above uses a different version of the template. <strong>Sorted&lt;int&gt;</strong> uses the primary template. <strong>Sorted&lt;string*&gt;</strong> uses the partial specialization for pointers. Last, <strong>Sorted&lt;char*&gt;</strong> uses the full specialization for <strong>char*</strong>. Without this full specialization, you could be fooled into thinking that things were working correctly because the <strong>words</strong> array would still sort out to "a big dog is running" since the partial specialization would end up comparing the first character of each array. However, <strong>words2</strong> would not sort correctly<sup>.</sup></p></section><section><title><p>Preventing template code bloat</p></title><p>Whenever a class template is instantiated, the code from the class definition for the particular specialization is generated, along with all the member functions that are called in the program. Only the member functions that are actually called are generated. This is a good thing, as the following program makes clear:<sup>.</sup></p><p>//: C05:DelayedInstantiation.cpp</p><p>// Member functions of class templates are not</p><p>// instantiated until they're needed.</p><empty-line/><p>class X {</p><p>public:</p><p>  void f() {}</p><p>};</p><empty-line/><p>class Y {</p><p>public:</p><p>  void g() {}</p><p>};</p><empty-line/><p>template &lt;typename T&gt; class Z {</p><p>  T t;</p><p>public:</p><p>  void a() { t.f(); }</p><p>  void b() { t.g(); }</p><p>};</p><empty-line/><p>int main() {</p><p>  Z&lt;X&gt; zx;</p><p>  zx.a(); // Doesn't create Z&lt;X&gt;::b()</p><p>  Z&lt;Y&gt; zy;</p><p>  zy.b(); // Doesn't create Z&lt;Y&gt;::a()</p><p>} ///:~</p><empty-line/><p>Here, even though the template <strong>Z</strong> purports to use both <strong>f( )</strong> and <strong>g( )</strong> member functions of <strong>T</strong>, the fact that the program compiles shows you that it only generates <strong>Z&lt;X&gt;::a( )</strong> when it is explicitly called for <strong>zx.</strong> (If <strong>Z&lt;X&gt;::b( )</strong> were also generated at the same time, a compile-time error message would be generated, because it would attempt to call <strong>X::g( )</strong>, which doesn’t exist.) Similarly, the call to <strong>zy.b( )</strong> doesn’t generate <strong>Z&lt;Y&gt;::a( )</strong>. As a result, the <strong>Z</strong> template can be used with <strong>X</strong> and <strong>Y;</strong> whereas if all the member functions were generated when the class was first created the use of many templates would significantly limited<sup>.</sup></p><p>Suppose you have a container, a <strong>Stack</strong> say, and you use specializations for <strong>int</strong>, <strong>int*</strong>, and <strong>char*</strong>. Three versions of <strong>Stack</strong> code will be generated and linked as part of your program. One of the reasons for using a template in the first place is so you don’t have to replicate code by hand; but code still gets replicated—it’s just the compiler that does it instead of you. You can factor the bulk of the implementation for storing pointer types into a single class by using a combination of full and partial specialization. The key is to fully specialize for <strong>void*</strong> and then derive all other pointer types from the <strong>void*</strong> implementation so the common code can be shared. The program below illustrates this technique<sup>.</sup></p><p>//: C05:Nobloat.h</p><p>// Shares code for storing pointers in a Stack</p><p>#ifndef NOBLOAT_H</p><p>#define NOBLOAT_H</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;cstring&gt;</p><empty-line/><p>// The primary template</p><p>template&lt;class T&gt;</p><p>class Stack {</p><p>  T* data;</p><p>  std::size_t count;</p><p>  std::size_t capacity;</p><p>  enum {INIT = 5};</p><p>public:</p><p>  Stack() {</p><p>    count = 0;</p><p>    capacity = INIT;</p><p>    data = new T[INIT];</p><p>  }</p><p>  void push(const T&amp; t) {</p><p>    if (count == capacity) {</p><p>      // Grow array store</p><p>      std::size_t newCapacity = 2*capacity;</p><p>      T* newData = new T[newCapacity];</p><p>      for (size_t i = 0; i &lt; count; ++i)</p><p>        newData[i] = data[i];</p><p>      delete [] data;</p><p>      data = newData;</p><p>      capacity = newCapacity;</p><p>    }</p><p>    assert(count &lt; capacity);</p><p>    data[count++] = t;</p><p>  }</p><p>  void pop() {</p><p>    assert(count &gt; 0);</p><p>    --count;</p><p>  }</p><p>  T top() const {</p><p>    assert(count &gt; 0);</p><p>    return data[count-1];</p><p>  }</p><p>  size_t size() const {return count;}</p><p>};</p><empty-line/><p>// Full specialization for void*</p><p>template&lt;&gt;</p><p>class Stack&lt;void *&gt; {</p><p>  void** data;</p><p>  std::size_t count;</p><p>  std::size_t capacity;</p><p>  enum {INIT = 5};</p><p>public:</p><p>  Stack() {</p><p>    count = 0;</p><p>    capacity = INIT;</p><p>    data = new void*[INIT];</p><p>  }</p><p>  void push(void* const &amp; t) {</p><p>    if (count == capacity) {</p><p>      std::size_t newCapacity = 2*capacity;</p><p>      void** newData = new void*[newCapacity];</p><p>      std::memcpy(newData, data, count*sizeof(void*));</p><p>      delete [] data;</p><p>      data = newData;</p><p>      capacity = newCapacity;</p><p>    }</p><p>    assert(count &lt; capacity);</p><p>    data[count++] = t;</p><p>  }</p><p>  void pop() {</p><p>    assert(count &gt; 0);</p><p>    --count;</p><p>  }</p><p>  void* top() const {</p><p>    assert(count &gt; 0);</p><p>    return data[count-1];</p><p>  }</p><p>  std::size_t size() const {return count;}</p><p>};</p><empty-line/><p>// Partial specialization for other pointer types</p><p>template&lt;class T&gt;</p><p>class Stack&lt;T*&gt; : private Stack&lt;void *&gt; {</p><p>  typedef Stack&lt;void *&gt; Base;</p><p>public:</p><p>  void push(T* const &amp; t) {Base::push(t);}</p><p>  void pop() {Base::pop();}</p><p>  T* top() const {return static_cast&lt;T*&gt;(Base::top());}</p><p>  std::size_t size() {return Base::size();}</p><p>};</p><p>#endif // NOBLOAT_H ///:~<sup>.</sup></p><empty-line/><p>This simple stack expands as it fills its capacity. The <strong>void*</strong> specialization stands out as a full specialization by virtue of the <strong>template&lt;&gt;</strong> prefix (that is, the template parameter list is empty). As mentioned earlier, it is necessary to implement all member functions in a class template specialization. The savings occurs with all other pointer types. The partial specialization for other pointer types derives from <strong>Stack&lt;void*&gt;</strong> privately, since we are merely using <strong>Stack&lt;void*&gt;</strong> for implementation purposes, and do not wish to expose any of its interface directly to the user. The member functions for each pointer instantiation are small forwarding functions to the corresponding functions in <strong>Stack&lt;void*&gt;</strong>. Hence, whenever a pointer type other than <strong>void*</strong> is instantiated, it is a fraction of the size it would have been had the primary template alone been used.<sup>[59]</sup> Here is a driver program:<sup>.</sup></p><p>//: C05:NobloatTest.cpp</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>#include "Nobloat.h"</p><p>using namespace std;</p><empty-line/><p>template&lt;class StackType&gt;</p><p>void emptyTheStack(StackType&amp; stk) {</p><p>  while (stk.size() &gt; 0) {</p><p>    cout &lt;&lt; stk.top() &lt;&lt; endl;</p><p>    stk.pop();</p><p>  }</p><p>}</p><p>// An overload for emptyTheStack (not a specialization!)</p><p>template&lt;class T&gt;</p><p>void emptyTheStack(Stack&lt;T*&gt;&amp; stk) {</p><p>  while (stk.size() &gt; 0) {</p><p>    cout &lt;&lt; *stk.top() &lt;&lt; endl;</p><p>    stk.pop();</p><p>  }</p><p>}</p><empty-line/><p>int main() {</p><p>  Stack&lt;int&gt; s1;</p><p>  s1.push(1);</p><p>  s1.push(2);</p><p>  emptyTheStack(s1);</p><empty-line/><p>  Stack&lt;int *&gt; s2;</p><p>  int i = 3;</p><p>  int j = 4;</p><p>  s2.push(&amp;i);</p><p>  s2.push(&amp;j);</p><p>  emptyTheStack(s2);</p><p>} ///:~</p><empty-line/><p>For convenience we have included two <strong>emptyStack</strong> function templates. Since function templates don’t support partial specialization, we provide overloaded templates. The second version of <strong>emptyStack</strong> is more specialized than the first, so it is chosen whenever pointer types are used. Three class templates are instantiated in this program: <strong>Stack&lt;int&gt;</strong>, <strong>Stack&lt;void*&gt;</strong>, and <strong>Stack&lt;int*&gt;</strong>. <strong>Stack&lt;void*&gt;</strong> is implicitly instantiated because <strong>Stack&lt;int*&gt;</strong> derives from it. If a program uses instantiations for many pointer types, the savings in code size over just using a single <strong>Stack</strong> template can be substantial<sup>.</sup></p></section></section><section><title><p>Name lookup issues</p></title><section><p>When the compiler encounters an identifier it must determine the type and scope (and in the case of variables, the lifetime) of the entity the identifier represents. This is common knowledge among software developers, but the plot thickens when templates are involved. Because not everything is known about a template when its definition is first seen by the compiler, the compiler must hold off until the template is instantiated before it can determine whether it is being used properly. This predicament leads to a two-phase process for template compilation<sup>.</sup></p></section><section><title><p>Names in templates</p></title><p>In the first phase the compiler parses the template definition looking for obvious syntax errors and resolving all the names it can. The names it can resolve during parsing are those that do not depend on template parameters, which the compiler takes care of through normal name lookup means (and also through argument-dependent lookup, discussed below, if necessary). The names it can’t resolve are the so-called <emphasis>dependent names</emphasis>, which are names that in some way depend on template parameters. These can’t be resolved until the template is instantiated with its actual arguments. Instantiation, therefore, is the second phase of template compilation. During this second phase, the compiler determines whether an explicit specialization of the template in question needs to be used instead of the primary template<sup>.</sup></p><p>Before you see an example, two more terms need to be defined. A <emphasis>qualified name</emphasis> is a name with a class-name prefix, a name with an object name and a dot operator, or a name with a pointer to an object and an arrow operator. Examples of qualified names are found in the following expressions:<sup>.</sup></p><p>MyClass::f();</p><p>x.f();</p><p>p-&gt;f();</p><empty-line/><p>We have used qualified names many times in this book, and most recently in connection with the <strong>typename</strong> keyword. These are called qualified names because the target names (like <strong>f</strong> above) are explicitly associated with a class, which tells the compiler where to look for the declarations of those names<sup>.</sup></p><p>The other term to discuss is <strong>argument-dependent lookup</strong><sup>[60]</sup> (ADL), which is a technique originally designed to simplify using non-member function calls (including operators) declared in namespaces. Consider the following simple code excerpt:<sup>.</sup></p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>//…</p><p>  std::string s("hello");</p><p>  std::cout &lt;&lt; s &lt;&lt; std::endl;</p><empty-line/><p>Note that there is no <strong>using namespace std;</strong> directive, which is the typical practice inside header files, for example. Without such a directive, it is necessary to use the <strong>std::</strong> qualifier on the items that are in the <strong>std</strong> namespace. We have, however, not qualified everything from <strong>std</strong> that we are using. Can you see what we have left unqualified?<sup>.</sup></p><p>We have not specified which operator functions to use. We want the following to happen, but we don’t want to have to type it!</p><p>std::operator&lt;&lt;(std::operator&lt;&lt;(std::cout,s),std::endl);</p><empty-line/><p>To make the original output statement work as desired, ADL specifies that when an unqualified function call appears and its declaration is not in (normal) scope, the namespaces (or class scopes) of each of its arguments are searched for a matching function declaration. In the original statement, the first function call is:<sup>.</sup></p><p>operator&lt;&lt;(std::cout, s);</p><empty-line/><p>Since there is no such function in scope in our original excerpt, the compiler notes that this function’s first argument (<strong>std::cout</strong>) is in the namespace <strong>std;</strong> so it adds that namespace to the list of scopes to search for a unique function that best matches the signature <strong>operator&lt;&lt;(std::ostream&amp;, std::string)</strong>. It finds this function declared in the <strong>std</strong> namespace via the <strong>&lt;string&gt;</strong> header, so that is the function that is called. Namespaces would be very inconvenient without ADL. (But note that, in general, ADL brings in <emphasis>all</emphasis> declarations of the name in question from all eligible namespaces—if there is no best match, an ambiguity will result.) To turn off ADL, you can enclose the function name in parentheses:<sup>.</sup></p><p>(f)(x, y);  // ADL suppressed</p><empty-line/><p>Now consider the following program, from a presentation by Herb Sutter:</p><p>// Lookup.cpp</p><p>// Only works on EDG and Metrowerks (special option)</p><p>#include &lt;iostream&gt;</p><p>using std::cout;</p><empty-line/><p>void f(double) { cout &lt;&lt; "f(double)\n"; }</p><empty-line/><p>template&lt;class T&gt;</p><p>class X {</p><p>public:</p><p>  void g() { f(1); }</p><p>};</p><empty-line/><p>void f(int) { cout &lt;&lt; "f(int)\n"; }</p><empty-line/><p>int main() {</p><p>  X&lt;int&gt;().g();</p><p>}</p><empty-line/><p>The only compiler we have that gets this correct right out of the box is the Edison Design Group front end. (A number of compilers use this front end, including Comeau C++.) The output should be:<sup>.</sup></p><p>f(double)</p><empty-line/><p>because <strong>f</strong> is a non-dependent name that can be resolved early by looking in the context where the template is defined, when only <strong>f(double)</strong> is in scope. Unfortunately, there is a lot of code in existence that depends on the non-standard behavior of binding the call to <strong>f(1)</strong> inside <strong>g( )</strong> to the latter <strong>f(int)</strong>, so compiler writers have been reluctant to make the change. (Some compilers, such as the Metrowerks compiler, have an option to enable the correct lookup behavior.)<sup>.</sup></p><p>Here is a more detailed example, also based on an example from Herb Sutter:</p><p>//: C05:Lookup2.cpp</p><p>//{-bor}</p><p>//{-g++}</p><p>// Microsoft: use option –Za (ANSI mode)</p><p>#include &lt;iostream&gt;</p><p>#include &lt;typeinfo&gt;</p><p>using std::cout;</p><p>using std::endl;</p><empty-line/><p>void g() { cout &lt;&lt; "global g()\n"; }</p><empty-line/><p>template &lt;class T&gt;</p><p>class Y {</p><p>public:</p><p>  void g() { cout &lt;&lt; "Y&lt;" &lt;&lt; typeid(T).name()</p><p>   &lt;&lt; "&gt;::g()\n"; }</p><p>  void h() { cout &lt;&lt; "Y&lt;" &lt;&lt; typeid(T).name()</p><p>   &lt;&lt; "&gt;::h()\n"; }</p><p>  typedef int E;</p><p>};</p><empty-line/><p>typedef double E;</p><empty-line/><p>template&lt;class T&gt;</p><p>void swap(T&amp; t1, T&amp; t2) {</p><p>  cout &lt;&lt; "global swap\n";</p><p>  T temp = t1;</p><p>  t1 = t2;</p><p>  t2 = temp;</p><p>}</p><empty-line/><p>template&lt;class T&gt;</p><p>class X : public Y&lt;T&gt; {</p><p>public:</p><p>  E f() {</p><p>    g();</p><p>    this-&gt;h();</p><p>    T t1 = T(), t2 = T(1);</p><p>    cout &lt;&lt; t1 &lt;&lt; endl;</p><p>    swap(t1, t2);</p><p>    std::swap(t1, t2);</p><p>    cout &lt;&lt; typeid(E).name() &lt;&lt; endl;</p><p>    return E(t2);</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  X&lt;int&gt; x;</p><p>  cout &lt;&lt; x.f() &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The output from this program should be:</p><p>global g()</p><p>Y&lt;int&gt;::h()</p><p>0</p><p>global swap</p><p>double</p><p>1</p><empty-line/><p>Looking at the declarations inside of <strong>X::f( )</strong>, we observe the following:</p><p>·         The return type of <strong>X::f( )</strong>, which is <strong>E</strong>, is not a dependent name, so it is looked up when the template is parsed, and the <strong>typedef</strong> naming <strong>E</strong> as a <strong>double</strong> is found. This may seem strange, since with non-template classes the declaration of <strong>E</strong> in the base class would be found first, but those are the rules. (The base class, <strong>Y</strong>, is a <emphasis>dependent base class</emphasis>, so it can’t be searched at template definition time)<sup>.</sup></p><p>·         The call to <strong>g( )</strong> is also non-dependent, since there is no mention of <strong>T</strong>. If <strong>g</strong> had parameters that were of class type of defined in another namespace, ADL would take over, since there is no <strong>g</strong> with parameters in scope. As it is, this call matches the global declaration of <strong>g( )</strong><sup><strong>.</strong></sup></p><p>·         The call <strong>this-&gt;h( )</strong> is a qualified name, and the object that qualifies it (<strong>this</strong>) refers to the current object, which is of type <strong>X</strong>, which in turn depends on the name <strong>Y&lt;T&gt;</strong> by inheritance. There is no function <strong>h( )</strong> inside of <strong>X</strong>, so lookup will naturally want to search the scope of <strong>X</strong>’s base class, <strong>Y&lt;T&gt;</strong>. Since this is a dependent name, it is looked up at instantiation time, when <strong>Y&lt;T&gt;</strong> can be reliably known (including any potential specializations that might have been written after the definition of <strong>X</strong>); so it calls <strong>Y&lt;int&gt;::h( )</strong><sup><strong>.</strong></sup></p><p>·         The declarations of <strong>t1</strong> and <strong>t2</strong> are dependent, of course<sup>.</sup></p><p>·         The call to <strong>operator&lt;&lt;(cout, t1)</strong> is dependent, since <strong>t1</strong> is of type <strong>T</strong>. This is looked up later when <strong>T</strong> is <strong>int</strong>, and the inserter for <strong>int</strong> is found in <strong>std</strong><sup><strong>.</strong></sup></p><p>·         The unqualified call to <strong>swap( )</strong> is dependent because its arguments are of type <strong>T</strong>. This ultimately causes a global <strong>swap(int&amp;, int&amp;)</strong> to be instantiated, of course<sup>.</sup></p><p>·         The qualified call to <strong>std::swap( )</strong> is <emphasis>not</emphasis> dependent, because <strong>std</strong> is a fixed namespace; so the compiler knows to look there for the proper declaration. (The qualifier on the left of the "<strong>::</strong>" must mention a template parameter for a qualified name to be considered dependent.) The <strong>std::swap( )</strong> function template later generates <strong>std::swap(int&amp;, int&amp;)</strong>, at instantiation time. No more dependent names remain in <strong>X&lt;T&gt;::f( )</strong><sup><strong>.</strong></sup></p><p>To clarify and summarize: name lookup is done at the point of instantiation if the name is dependent, except that for unqualified dependent names the normal name lookup is also attempted early, at the point of definition. All non-dependent names in templates are looked up early, at the time the template definition is parsed. (If necessary, another lookup occurs at instantiation time, when the type of the actual argument is known.)<sup>.</sup></p><p>(Whew!) If you have studied this example to the point that you understand it, prepare yourself for yet another surprise in the next section when <strong>friend</strong> declarations enter the picture.</p></section><section><title><p>Templates and friends</p></title><section><p>A friend function declaration inside a class allows a non-member function to access non-public members of that class. If the friend function name is qualified, it will of course be found in the namespace or class that qualifies it. If it is unqualified, however, the compiler must make an assumption about where the definition of the friend function will be, since all identifiers must have a unique scope. The expectation is that the function will be defined in the nearest enclosing namespace (non-class) scope that contains the class granting friendship. Often this is just the global scope. The following non-template example clarifies this issue<sup>.</sup></p><p>//: C05:FriendScope.cpp</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Friendly {</p><p>  int i;</p><p>public:</p><p>  Friendly(int theInt) { i = theInt; }</p><p>  friend void f(const Friendly&amp;); // needs global def.</p><p>  void g() { f(*this); }</p><p>};</p><empty-line/><p>void h() {</p><p>  f(Friendly(1));  // uses ADL</p><p>}</p><empty-line/><p>void f(const Friendly&amp; fo) {  // definition of friend</p><p>  cout &lt;&lt; fo.i &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main() {</p><p>  h();// prints 1</p><p>  Friendly(2).g();   // prints 2</p><p>} ///:~</p><empty-line/><p>The declaration of <strong>f( )</strong> inside the <strong>Friendly</strong> class is unqualified, so the compiler will expect to be able to eventually link that declaration to a definition at file scope (the namespace scope that contains <strong>Friendly</strong> in this case). That definition appears after the definition of the function <strong>h( )</strong>. The linking of the call to <strong>f( )</strong> inside <strong>h( )</strong> to the same function is a separate matter, however. This is resolved by ADL. Since the argument of <strong>f( )</strong> inside <strong>h( )</strong> is a <strong>Friendly</strong> object, the <strong>Friendly</strong> class is searched for a declaration of <strong>f( )</strong>, which succeeds. If the call were <strong>f(1)</strong> instead (which makes some sense since 1 can be implicitly converted to <strong>Friendly(1)</strong>), the call should fail, since there is no hint of where the compiler should look for the declaration of <strong>f( )</strong>. The EDG compiler correctly complains that <strong>f</strong> is undefined in that case<sup>.</sup></p><p>Now suppose that <strong>Friendly</strong> and <strong>f</strong> are both templates, as in the following program.</p><p>//: C05:FriendScope2.cpp</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><p>// Necessary forward declarations</p><p>template&lt;class T&gt;</p><p>class Friendly;</p><p>template&lt;class T&gt;</p><p>void f(const Friendly&lt;T&gt;&amp;);</p><empty-line/><p>template&lt;class T&gt;</p><p>class Friendly {</p><p>  T t;</p><p>public:</p><p>  Friendly(const T&amp; theT) : t(theT) {}</p><p>  friend void f&lt;&gt;(const Friendly&lt;T&gt;&amp;);</p><p>  void g() { f(*this); }</p><p>};</p><empty-line/><p>void h() {</p><p>  f(Friendly&lt;int&gt;(1));</p><p>}</p><empty-line/><p>template&lt;class T&gt;</p><p>void f(const Friendly&lt;T&gt;&amp; fo) {</p><p>  cout &lt;&lt; fo.t &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main() {</p><p>  h();</p><p>  Friendly&lt;int&gt;(2).g();</p><p>} ///:~</p><empty-line/><p>First notice that angle brackets in the declaration of <strong>f</strong> inside <strong>Friendly</strong>. This is necessary to tell the compiler that <strong>f</strong> is a template. Otherwise, the compiler will look for an ordinary function named <strong>f</strong> and of course not find it. We could have inserted the template parameter (<strong>&lt;T&gt;</strong>) in the brackets, but it is easily deduced from the declaration<sup>.</sup></p><p>The forward declaration of the function template <strong>f</strong> before the class definition is necessary, even though it wasn’t in the previous example when <strong>f</strong> was a not a template; the language specifies that friend function templates must be previously declared. Of course, to properly declare <strong>f</strong>, <strong>Friendly</strong> must also have been declared, since <strong>f</strong> takes a <strong>Friendly</strong> argument, hence the forward declaration of <strong>Friendly</strong> in the beginning. We could have placed the full definition of <strong>f</strong> right after the initial declaration of <strong>Friendly</strong> instead of separating its definition and declaration, but we chose instead to leave it in a form that more closely resembles the previous example<sup>.</sup></p><p>One last option remains for using friends inside templates: fully define them inside the class itself. Here is how the previous example would appear with that change:</p><p>//: C05:FriendScope3.cpp</p><p>//{-bor}</p><p>// Microsoft: use the -Za (ANSI-compliant) option</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T&gt;</p><p>class Friendly {</p><p>  T t;</p><p>public:</p><p>  Friendly(const T&amp; theT) : t(theT) {}</p><p>  friend void f(const Friendly&lt;T&gt;&amp; fo) {</p><p>    cout &lt;&lt; fo.t &lt;&lt; endl;</p><p>}</p><p>  void g() { f(*this); }</p><p>};</p><empty-line/><p>void h() {</p><p>  f(Friendly&lt;int&gt;(1));</p><p>}</p><empty-line/><p>int main() {</p><p>  h();</p><p>  Friendly&lt;int&gt;(2).g();</p><p>} ///:~</p><empty-line/><p>There is an important difference between this and the previous example: <strong>f</strong> is not a template here, but is an ordinary function. (Remember that angle brackets were necessary before to imply that <strong>f</strong> was a template.) Every time the <strong>Friendly</strong> class template is instantiated, a new, ordinary function overload is created that takes an argument of the current <strong>Friendly</strong> specialization. This is what Dan Saks has called "making new friends."<sup>[61]</sup> This is the most convenient way to define friend functions for templates<sup>.</sup></p><p>To make this perfectly clear, suppose you have a class template to which you want to add non-member operators as friends. Here is a class template that simply holds a generic value:</p><p>template&lt;class T&gt;</p><p>class Box {</p><p>  T t;</p><p>public:</p><p>  Box(const T&amp; theT) : t(theT) {}</p><p>};</p><empty-line/><p>Without understanding the likes of the previous examples in this section, novices find themselves frustrated because they can’t get a simple stream output inserter to work. If you don’t define your operators inside the definition of <strong>Box</strong>, you must provide the forward declarations we showed earlier:<sup>.</sup></p><p>//: C05:Box1.cpp</p><p>// Defines template operators</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><p>// Forward declarations</p><p>template&lt;class T&gt;</p><p>class Box;</p><p>template&lt;class T&gt;</p><p>Box&lt;T&gt; operator+(const Box&lt;T&gt;&amp;, const Box&lt;T&gt;&amp;);</p><p>template&lt;class T&gt;</p><p>ostream&amp; operator&lt;&lt;(ostream&amp;, const Box&lt;T&gt;&amp;);</p><empty-line/><p>template&lt;class T&gt;</p><p>class Box {</p><p>  T t;</p><p>public:</p><p>  Box(const T&amp; theT) : t(theT) {}</p><p>  friend Box operator+&lt;&gt;(const Box&lt;T&gt;&amp;, const Box&lt;T&gt;&amp;);</p><p>  friend ostream&amp; operator&lt;&lt; &lt;&gt;(ostream&amp;, const Box&lt;T&gt;&amp;);</p><p>};</p><empty-line/><p>template&lt;class T&gt;</p><p>Box&lt;T&gt; operator+(const Box&lt;T&gt;&amp; b1, const Box&lt;T&gt;&amp; b2) {</p><p>  return Box&lt;T&gt;(b1.t + b2.t);</p><p>}</p><empty-line/><p>template&lt;class T&gt;</p><p>ostream&amp; operator&lt;&lt;(ostream&amp; os, const Box&lt;T&gt;&amp; b) {</p><p>  return os &lt;&lt; '[' &lt;&lt; b.t &lt;&lt; ']';</p><p>}</p><empty-line/><p>int main() {</p><p>  Box&lt;int&gt; b1(1), b2(2);</p><p>  cout &lt;&lt; b1 + b2 &lt;&lt; endl;  // [3]</p><p>//  cout &lt;&lt; b1 + 2 &lt;&lt; endl; // no implicit conversions!</p><p>} ///:~</p><empty-line/><p>Here we are defining both an addition operator and an output stream operator. The main program reveals a disadvantage of this approach: you can’t depend on implicit conversions (see the expression <strong>b1 + 2</strong>) because templates do not provide them. Using the in-class, non-template approach is shorter and more robust:<sup>.</sup></p><p>//: C05:Box2.cpp</p><p>// Defines non-template operators</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T&gt;</p><p>class Box {</p><p>  T t;</p><p>public:</p><p>  Box(const T&amp; theT) : t(theT) {}</p><p>  friend Box operator+(const Box&lt;T&gt;&amp; b1,</p><p>          const Box&lt;T&gt;&amp; b2) {</p><p>    return Box&lt;T&gt;(b1.t + b2.t);</p><p>  }</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os,</p><p>                const Box&lt;T&gt;&amp; b) {</p><p>    return os &lt;&lt; '[' &lt;&lt; b.t &lt;&lt; ']';</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  Box&lt;int&gt; b1(1), b2(2);</p><p>  cout &lt;&lt; b1 + b2 &lt;&lt; endl;  // [3]</p><p>  cout &lt;&lt; b1 + 2 &lt;&lt; endl;   // [3]</p><p>} ///:~</p><empty-line/><p>Because the operators are normal functions (overloaded for each specialization of <strong>Box</strong>—just <strong>int</strong> in this case, of course), implicit conversions are applied as normal; so the expression <strong>b1 + 2</strong> is valid<sup>.</sup></p></section><section><section><title><p>Friend templates</p></title><p>You can be precise as to which specializations of a template are friends of a class. In the examples in the previous section, only the specialization of the function template <strong>f</strong> with the same type that specialized <strong>Friendly</strong> was a friend. For example, only the specialization <strong>f&lt;int&gt;(const Friendly&lt;int&gt;&amp;)</strong> is a friend of the class <strong>Friendly&lt;int&gt;</strong>. This was accomplished by using the template parameter for <strong>Friendly</strong> to specialize <strong>f</strong> in its friend declaration. If we had wanted to, we could have made a particular, fixed specialization of <strong>f</strong> a friend to all instances of <strong>Friendly</strong>, like this:<sup>.</sup></p><p>// Inside Friendly:</p><p>  friend void f&lt;&gt;(const Friendly&lt;double&gt;&amp;);</p><empty-line/><p>By using <strong>double</strong> instead of <strong>T</strong>, the <strong>double</strong> specialization of <strong>f</strong> has access to the non-public members of any <strong>Friendly</strong> specialization. The specialization <strong>f&lt;double&gt;( )</strong> still isn’t instantiated unless it is explicitly called, of course<sup>.</sup></p><p>Likewise, if you were to declare a non-template function with no parameters dependent on <strong>T</strong>, that single function would be a friend to all instances of <strong>Friendly</strong>:<sup>.</sup></p><p>// Inside of Friendly:</p><p>  friend void g(int);  // g(int) befriends all Friendly’s</p><empty-line/><p>As always, since <strong>g(int)</strong> is unqualified, it must be defined at file scope (the namespace scope containing <strong>Friendly</strong>)<sup>.</sup></p><p>It is also possible to arrange for all specializations of <strong>f</strong> to be friends for all specializations of <strong>Friendly</strong>, with a so-called <emphasis>friend template</emphasis>, as follows:</p><p>template&lt;class T&gt;</p><p>class Friendly {</p><p>  template&lt;class U&gt; friend void f&lt;&gt;(const Friendly&lt;U&gt;&amp;);</p><empty-line/><p>Since the template argument for the friend declaration is independent of <strong>T</strong>, any combination of <strong>T</strong> and <strong>U</strong> is allowed, achieving the friendship objective. Like member templates, friend templates can appear within non-template classes as well<sup>.</sup></p></section></section></section></section><section><title><p>Template programming idioms</p></title><section><p>Since language is a tool of thought, new language features tend to spawn new programming techniques. In this section we cover some commonly-used template programming idioms that have emerged in the years since templates were added to the C++ language.<sup>[62]</sup></p></section><section><title><p>Traits</p></title><p>The traits template technique, pioneered by Nathan Myers, is a means of bundling type-dependent declarations together. In essence, using traits allows you to "mix and match" certain types and values with contexts that use them in a flexible manner, while keeping your code readable and maintainable<sup>.</sup></p><p>The simplest example of a traits template is the <strong>numeric_limits</strong> class template defined in <strong>&lt;limits&gt;</strong>. The primary template is defined as follows:</p><p>template&lt;class T&gt; class numeric_limits {</p><p>public:</p><p>  static const bool is_specialized = false;</p><p>  static T min() throw();</p><p>  static T max() throw();</p><p>  static const int digits = 0;</p><p>  static const int digits10 = 0;</p><p>  static const bool is_signed = false;</p><p>  static const bool is_integer = false;</p><p>  static const bool is_exact = false;</p><p>  static const int radix = 0;</p><p>  static T epsilon() throw();</p><p>  static T round_error() throw();</p><p>  static const int min_exponent = 0;</p><p>  static const int min_exponent10 = 0;</p><p>  static const int max_exponent = 0;</p><p>  static const int max_exponent10 = 0;</p><p>  static const bool has_infinity = false;</p><p>  static const bool has_quiet_NaN = false;</p><p>  static const bool has_signaling_NaN = false;</p><p>  static const float_denorm_style has_denorm =</p><p>                   denorm_absent;</p><p>  static const bool has_denorm_loss = false;</p><p>  static T infinity() throw();</p><p>  static T quiet_NaN() throw();</p><p>  static T signaling_NaN() throw();</p><p>  static T denorm_min() throw();</p><p>  static const bool is_iec559 = false;</p><p>  static const bool is_bounded = false;</p><p>  static const bool is_modulo = false;</p><p>  static const bool traps = false;</p><p>  static const bool tinyness_before = false;</p><p>  static const float_round_style round_style =</p><p>                  round_toward_zero;</p><p>};</p><empty-line/><p>The <strong>&lt;limits&gt;</strong> header defines specializations for all fundamental, numeric types (in which case the member <strong>is_specialized</strong> is set to <strong>true</strong>). To obtain the base for the <strong>double</strong> version of your floating-point number system, for example, you can use the expression <strong>numeric_limits&lt;double&gt;::radix</strong>. To find the smallest integer value available, you can use <strong>numeric_limits&lt;int&gt;::min( )</strong>. Not all members of <strong>numeric_limits</strong> apply to all fundamental types, of course. (For example, <strong>epsilon( )</strong> is only for floating-point types.)<sup>.</sup></p><p>The values that will always be integral are static data members of <strong>numeric_limits</strong>; those that may not be integral, such as the minimum value for <strong>float</strong>, are implemented as static inline member functions. This is because C++ allows only <emphasis>integral</emphasis> static data member constants to be initialized inside a class definition. Other members, such as floating-point values, must be initialized at file scope outside the class definition, which is not appropriate in a header file. Since the needed value in that case will be placed in an implementation (.cpp) file, the value will not be available for compile-time optimization. Inline member functions of a class template, on the other hand, can be included in a header file, and thus facilitate compile-time optimization<sup>.</sup></p><p>In Chapter 3 you saw how traits are used to control the character-processing functionality used by the string classes. The classes <strong>std::string</strong> and <strong>std::wstring</strong> are specializations of the <strong>std::basic_string</strong> template, which is defined as follows:</p><p>template&lt;class charT,</p><p>  class traits = char_traits&lt;charT&gt;,</p><p>  class allocator = allocator&lt;charT&gt; &gt;</p><p>  class basic_string;</p><empty-line/><p>The template parameter <strong>charT</strong> represents the underlying character type, which is usually either <strong>char</strong> or <strong>wchar_t</strong>. The primary <strong>char_traits</strong> template is typically empty, and specializations for <strong>char</strong> and <strong>wchar_t</strong> are provided by the standard library. Here is the specification of the specialization <strong>char_traits&lt;char&gt;</strong> according to the C++ standard:<sup>.</sup></p><p>template&lt;&gt;</p><p>struct char_traits&lt;char&gt; {</p><p>  typedef char char_type;</p><p>  typedef int int_type;</p><p>  typedef streamoff off_type;</p><p>  typedef streampos pos_type;</p><p>  typedef mbstate_t state_type;</p><p>  static void assign(char_type&amp; c1, const char_type&amp; c2);</p><p>  static bool eq(const char_type&amp; c1, const char_type&amp; c2);</p><p>  static bool lt(const char_type&amp; c1, const char_type&amp; c2);</p><p>  static int compare(const char_type* s1,</p><p>      const char_type* s2, size_t n);</p><p>  static size_t length(const char_type* s);</p><p>  static const char_type* find(const char_type* s,</p><p>                size_t n,</p><p>                const char_type&amp; a);</p><p>  static char_type* move(char_type* s1,</p><p>          const char_type* s2, size_t n);</p><p>  static char_type* copy(char_type* s1,</p><p>          const char_type* s2, size_t n);</p><p>  static char_type* assign(char_type* s, size_t n,</p><p>            char_type a);</p><p>  static int_type not_eof(const int_type&amp; c);</p><p>  static char_type to_char_type(const int_type&amp; c);</p><p>  static int_type to_int_type(const char_type&amp; c);</p><p>  static bool eq_int_type(const int_type&amp; c1,</p><p>           const int_type&amp; c2);</p><p>  static int_type eof();</p><p>};</p><empty-line/><p>These functions are used by the <strong>basic_string</strong> class template for character-based operations common to string processing. When you declare a <strong>string</strong> variable, such as:<sup>.</sup></p><p>std::string s;</p><empty-line/><p>you are actually declaring <strong>s</strong> as follows (because of the default template arguments in the specification of <strong>basic_string</strong>):</p><p>std::basic_string&lt;char, std::char_traits&lt;char&gt;,</p><p>   std::allocator&lt;char&gt; &gt; s;</p><empty-line/><p>Because the character traits have been separated from the <strong>basic_string</strong> class template, you can supply a custom traits class to replace <strong>std::char_traits</strong>. The following example illustrates this flexibility<sup>.</sup></p><p>//: C05:PoohCorner.cpp</p><p>// Illustrates traits classes</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>// Item classes (traits of guests):</p><p>class Water {</p><p>public:</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Water&amp;) {</p><p>    return os &lt;&lt; "Water";</p><p>  }</p><p>};</p><p>class Milk {</p><p>public:</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Milk&amp;) {</p><p>    return os &lt;&lt; "Milk";</p><p>  }</p><p>};</p><p>class Honey {</p><p>public:</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Honey&amp;) {</p><p>    return os &lt;&lt; "Honey";</p><p>  }</p><p>};</p><p>class Cookies {</p><p>public:</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Cookies&amp;) {</p><p>    return os &lt;&lt; "Cookies";</p><p>  }</p><p>};</p><empty-line/><p>// Guest classes:</p><p>class Bear {</p><p>public:</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Bear&amp;) {</p><p>    return os &lt;&lt; "Pooh";</p><p>  }</p><p>};</p><p>class Boy {</p><p>public:</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Boy&amp;) {</p><p>    return os &lt;&lt; "Christopher Robin";</p><p>  }</p><p>};</p><empty-line/><p>// Primary traits template (empty—could hold common types)</p><p>template&lt;class Guest&gt;</p><p>class GuestTraits;</p><empty-line/><p>// Traits specializations for Guest types</p><p>template&lt;&gt;</p><p>class GuestTraits&lt;Bear&gt; {</p><p>public:</p><p>  typedef Water beverage_type;</p><p>  typedef Honey snack_type;</p><p>};</p><p>template&lt;&gt;</p><p>class GuestTraits&lt;Boy&gt; {</p><p>public:</p><p>  typedef Milk beverage_type;</p><p>  typedef Cookies snack_type;</p><p>};</p><empty-line/><p>// A custom traits class</p><p>class MixedUpTraits {</p><p>public:</p><p>  typedef Milk beverage_type;</p><p>  typedef Honey snack_type;</p><p>};</p><empty-line/><p>// The Guest template (uses a traits class)</p><p>template&lt; class Guest, class traits = GuestTraits&lt;Guest&gt; &gt;</p><p>class PoohCorner {</p><p>  Guest theGuest;</p><p>  typedef typename traits::beverage_type beverage_type;</p><p>  typedef typename traits::snack_type snack_type;</p><p>  beverage_type bev;</p><p>  snack_type snack;</p><p>public:</p><p>  PoohCorner(const Guest&amp; g)</p><p>    : theGuest(g), bev(beverage_type()),</p><p>      snack(snack_type()) {}</p><p>  void entertain() {</p><p>    cout &lt;&lt; "Entertaining " &lt;&lt; theGuest</p><p>         &lt;&lt; " serving " &lt;&lt; bev</p><p>         &lt;&lt; " and " &lt;&lt; snack &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  Boy cr;</p><p>  PoohCorner&lt;Boy&gt; pc1(cr);</p><p>  pc1.entertain();</p><p>  Bear pb;</p><p>  PoohCorner&lt;Bear&gt; pc2(pb);</p><p>  pc2.entertain();</p><p>  PoohCorner&lt;Bear, MixedUpTraits&gt; pc3(pb);</p><p>  pc3.entertain();</p><p>} ///:~<sup>.</sup></p><empty-line/><p>In this program, instances of the guest classes <strong>Boy</strong> and <strong>Bear</strong> are served items appropriate to their tastes. <strong>Boy</strong>s like milk and cookies and <strong>Bear</strong>s like water and honey. This association of guests to items is done via specializations of a primary (empty) traits class template. The default arguments to <strong>PoohCorner</strong> ensure that guests get their proper items, but you can override this by simply providing a class that meets the requirements of the traits class, as we do with the <strong>MixedUpTraits</strong> class above. The output of this program is:<sup>.</sup></p><p>Entertaining Christopher Robin serving Milk and Cookies</p><p>Entertaining Pooh serving Water and Honey</p><p>Entertaining Pooh serving Milk and Honey</p><empty-line/><p>Using traits provides two key advantages: (1) it allows flexibility in pairing objects with associated attributes or functionality, and (2) it keeps template parameter lists small and readable. If 30 types were associated with a guest, it would be inconvenient to have to specify all 30 arguments directly in each <strong>PoohCorner</strong> declaration. Factoring the types into a separate traits class simplifies things considerably<sup>.</sup></p><p>The traits technique is also used in implementing streams and locales, as we showed in Chapter 4.</p></section><section><title><p>Policies</p></title><p>If you inspect the <strong>char_traits</strong> specialization for <strong>wchar_t</strong>, you’ll see that it is practically identical to its <strong>char</strong> counterpart:</p><p>template&lt;&gt;</p><p>  struct char_traits&lt;wchar_t&gt; {</p><p>  typedef wchar_t char_type;</p><p>  typedef wint_t int_type;</p><p>  typedef streamoff off_type;</p><p>  typedef wstreampos pos_type;</p><p>  typedef mbstate_t state_type;</p><p>  static void assign(char_type&amp; c1, const char_type&amp; c2);</p><p>  static bool eq(const char_type&amp; c1, const char_type&amp; c2);</p><p>  static bool lt(const char_type&amp; c1, const char_type&amp; c2);</p><p>  static int compare(const char_type* s1,</p><p>      const char_type*  s2, size_t n);</p><p>  static size_t length(const char_type* s);</p><p>  static const char_type* find(const char_type* s,</p><p>                size_t n,</p><p>                const char_type&amp; a);</p><p>  static char_type* move(char_type* s1,</p><p>          const char_type* s2, size_t n);</p><p>  static char_type* copy(char_type* s1,</p><p>          const char_type* s2, size_t n);</p><p>  static char_type* assign(char_type* s, size_t n,</p><p>            char_type a);</p><p>  static int_type not_eof(const int_type&amp; c);</p><p>  static char_type to_char_type(const int_type&amp; c);</p><p>  static int_type to_int_type(const char_type&amp; c);</p><p>  static bool eq_int_type(const int_type&amp; c1,</p><p>           const int_type&amp; c2);</p><p>  static int_type eof();</p><p>};</p><empty-line/><p>The only real difference between the two versions is the set of types involved (<strong>char</strong> and <strong>int</strong> vs. <strong>wchar_t</strong> and <strong>wint_t</strong>). The functionality provided is the same.<sup>[63]</sup> This highlights the fact that traits classes are indeed for <emphasis>traits</emphasis>, and therefore the things that change between related traits classes are usually types and constant values, or fixed algorithms that use type-related template parameters. Traits classes tend to be templates themselves, since the types and constants they contain are seen as characteristics of the primary template parameter(s) (for example, <strong>char</strong> and <strong>wchar_t</strong>)<sup>.</sup></p><p>It is also useful to be able to associate <emphasis>functionality</emphasis> with template arguments, so that client programmers can easily customize behavior when they code. The following version of the <strong>PoohCorner</strong> program, for instance, supports different types of entertainment:<sup>.</sup></p><p>//: C05:PoohCorner2.cpp</p><p>// Illustrates policy classes</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>// Item classes:</p><p>class Water {</p><p>public:</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Water&amp;) {</p><p>    return os &lt;&lt; "Water";</p><p>  }</p><p>};</p><p>class Milk {</p><p>public:</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Milk&amp;) {</p><p>    return os &lt;&lt; "Milk";</p><p>  }</p><p>};</p><p>class Honey {</p><p>public:</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Honey&amp;) {</p><p>    return os &lt;&lt; "Honey";</p><p>  }</p><p>};</p><p>class Cookies {</p><p>public:</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Cookies&amp;) {</p><p>    return os &lt;&lt; "Cookies";</p><p>  }</p><p>};</p><empty-line/><p>// Guest classes:</p><p>class Bear {</p><p>public:</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Bear&amp;) {</p><p>    return os &lt;&lt; "Pooh";</p><p>  }</p><p>};</p><p>class Boy {</p><p>public:</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Boy&amp;) {</p><p>    return os &lt;&lt; "Christopher Robin";</p><p>  }</p><p>};</p><empty-line/><p>// Traits template</p><p>template&lt;class Guest&gt;</p><p>class GuestTraits;</p><empty-line/><p>// Traits specializations for Guest types</p><p>template&lt;&gt;</p><p>class GuestTraits&lt;Bear&gt; {</p><p>public:</p><p>  typedef Water beverage_type;</p><p>  typedef Honey snack_type;</p><p>};</p><p>template&lt;&gt;</p><p>class GuestTraits&lt;Boy&gt; {</p><p>public:</p><p>  typedef Milk beverage_type;</p><p>  typedef Cookies snack_type;</p><p>};</p><empty-line/><p>// Policy classes (require a static doAction() function)</p><p>class Feed {</p><p>public:</p><p>  static const char* doAction() {</p><p>    return "Feeding";</p><p>  }</p><p>};</p><p>class Stuff {</p><p>public:</p><p>  static const char* doAction() {</p><p>    return "Stuffing";</p><p>  }</p><p>};</p><empty-line/><p>// The Guest template (uses a policy and a traits class)</p><p>template&lt; class Guest, class Action, class traits =</p><p>                      GuestTraits&lt;Guest&gt; &gt;</p><p>class PoohCorner {</p><p>  Guest theGuest;</p><p>  typedef typename traits::beverage_type beverage_type;</p><p>  typedef typename traits::snack_type snack_type;</p><p>  beverage_type bev;</p><p>  snack_type snack;</p><p>public:</p><p>  PoohCorner(const Guest&amp; g)</p><p>    : theGuest(g), bev(beverage_type()), snack(snack_type()) {}</p><p>  void entertain() {</p><p>    cout &lt;&lt; Action::doAction() &lt;&lt; " " &lt;&lt; theGuest</p><p>         &lt;&lt; " with " &lt;&lt; bev</p><p>         &lt;&lt; " and " &lt;&lt; snack &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  Boy cr;</p><p>  PoohCorner&lt;Boy, Feed&gt; pc1(cr);</p><p>  pc1.entertain();</p><p>  Bear pb;</p><p>  PoohCorner&lt;Bear, Stuff&gt; pc2(pb);</p><p>  pc2.entertain();</p><p>} ///:~<sup>.</sup></p><empty-line/><p>The <strong>Action</strong> template parameter in the <strong>PoohCorner</strong> class expects to have a static member function named <strong>doAction( )</strong>, which is used in <strong>PoohCorner&lt;&gt;::entertain( )</strong>. Users can choose <strong>Feed</strong> or <strong>Stuff</strong> at will, both of which provide the required function. Classes that encapsulate functionality in this way are referred to as <emphasis>policy classes</emphasis>. The entertainment "policies" are provided above through <strong>Feed::doAction( )</strong> and <strong>Stuff::doAction( )</strong>. These policy classes happen to be ordinary classes, but they can be templates, and can be combined with inheritance to great advantage. For more in-depth information on policy-based design, see is Andrei Alexandrescu’s book,<sup>[64]</sup> the definitive source<sup>.</sup></p></section><section><title><p>The curiously recurring template pattern</p></title><p>Any novice C++ programmer can figure out how to modify a class to keep track of the number of objects of that class that currently exist. All you have to do is to add static members, and modify constructor and destructor logic, as follows:<sup>.</sup></p><p>//: C05:CountedClass.cpp</p><p>// Object counting via static members</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class CountedClass {</p><p>  static int count;</p><p>public:</p><p>  CountedClass() { ++count; }</p><p>  CountedClass(const CountedClass&amp;) { ++count; }</p><p>  ~CountedClass() { --count; }</p><p>  static int getCount() { return count; }</p><p>};</p><empty-line/><p>int CountedClass::count = 0;</p><empty-line/><p>int main() {</p><p>  CountedClass a;</p><p>  cout &lt;&lt; CountedClass::getCount() &lt;&lt; endl;   // 1</p><p>  CountedClass b;</p><p>  cout &lt;&lt; CountedClass::getCount() &lt;&lt; endl;   // 2</p><p>  { // an arbitrary scope:</p><p>    CountedClass c(b);</p><p>    cout &lt;&lt; CountedClass::getCount() &lt;&lt; endl; // 3</p><p>    a = c;</p><p>    cout &lt;&lt; CountedClass::getCount() &lt;&lt; endl; // 3</p><p>  }</p><p>  cout &lt;&lt; CountedClass::getCount() &lt;&lt; endl;   // 2</p><p>} ///:~<sup>.</sup></p><empty-line/><p>All constructors of <strong>CountedClass</strong> increment the static data member <strong>count</strong>, and the destructor decrements it. The static member function <strong>getCount( )</strong> yields the number of current objects whenever it called<sup>.</sup></p><p>It would be tremendously tedious to have to manually add these members every time you wanted to add object counting to a class. What is the usual object-oriented device to which one turns to repeat or share code? It’s inheritance, of course, which, unfortunately, is only half a solution in this case. Observe what happens when we collect the counting logic into a base class<sup>.</sup></p><p>//: C05:CountedClass2.cpp</p><p>// Erroneous attempt to count objects</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Counted {</p><p>  static int count;</p><p>public:</p><p>  Counted() { ++count; }</p><p>  Counted(const Counted&amp;) { ++count; }</p><p>  ~Counted() { --count; }</p><p>  static int getCount() { return count; }</p><p>};</p><p>int Counted::count = 0;</p><empty-line/><p>class CountedClass : public Counted {};</p><p>class CountedClass2 : public Counted {};</p><empty-line/><p>int main() {</p><p>  CountedClass a;</p><p>  cout &lt;&lt; CountedClass::getCount() &lt;&lt; endl;    // 1</p><p>  CountedClass b;</p><p>  cout &lt;&lt; CountedClass::getCount() &lt;&lt; endl;    // 2</p><p>  CountedClass2 c;</p><p>  cout &lt;&lt; CountedClass2::getCount() &lt;&lt; endl;   // 3 (Error)</p><p>} ///:~</p><empty-line/><p>All classes that derive from <strong>Counted</strong> share the same, single static data member, so the number of objects is tracked collectively across all classes in the <strong>Counted</strong> hierarchy. What is needed is a way to automatically generate a <emphasis>different</emphasis> base class for each derived class. This is accomplished by the curious template construct illustrated below:<sup>.</sup></p><p>//: C05:CountedClass3.cpp</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T&gt;</p><p>class Counted {</p><p>  static int count;</p><p>public:</p><p>  Counted() { ++count; }</p><p>  Counted(const Counted&lt;T&gt;&amp;) { ++count; }</p><p>  ~Counted() { --count; }</p><p>  static int getCount() { return count; }</p><p>};</p><p>template&lt;class T&gt;</p><p>int Counted&lt;T&gt;::count = 0;</p><empty-line/><p>// Curious class definitions</p><p>class CountedClass : public Counted&lt;CountedClass&gt; {};</p><p>class CountedClass2 : public Counted&lt;CountedClass2&gt; {};</p><empty-line/><p>int main() {</p><p>  CountedClass a;</p><p>  cout &lt;&lt; CountedClass::getCount() &lt;&lt; endl;    // 1</p><p>  CountedClass b;</p><p>  cout &lt;&lt; CountedClass::getCount() &lt;&lt; endl;    // 2</p><p>  CountedClass2 c;</p><p>  cout &lt;&lt; CountedClass2::getCount() &lt;&lt; endl;   // 1 (!)</p><p>} ///:~<sup>.</sup></p><empty-line/><p>Each derived class derives from a unique base class that is determined by using itself (the derived class) as a template parameter! This may seem like a circular definition, and it would be, had any base class members used the template argument in a computation. Since all data members of <strong>Counted</strong> are not dependent on <strong>T</strong>, its size (which is zero!) is known when the template is parsed. It doesn’t matter, therefore, which argument is used to instantiate <strong>Counted</strong>; its size is always the same. Therefore, any derivation from an instance of <strong>Counted</strong> can be completed when it is parsed, and there is no recursion. Since each base class is unique, it has its own static data, thus constituting a handy technique for adding counting to any class whatsoever. Jim Coplien was the first to mention this interesting derivation idiom in print, which he cited in an article, entitled "Curiously Recurring Template Patterns."[ ]<sup>[65]</sup></p></section></section><section><title><p>Template metaprogramming</p></title><section><p>In 1993 compilers were beginning to support simple template constructs so that users could define generic containers and functions. About the same time that the STL was being considered for adoption into standard C++, clever and surprising examples such as the following were passed around among members of the standards committee:<sup>.</sup></p><p>//: C05:Factorial.cpp</p><p>// Compile-time computation!</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><p>template&lt;int n&gt;</p><p>struct Factorial {</p><p>   enum {val = Factorial&lt;n-1&gt;::val * n};</p><p>};</p><p>template&lt;&gt;</p><p>struct Factorial&lt;0&gt; {</p><p>   enum {val = 1};</p><p>};</p><p>int main() {</p><p>   cout &lt;&lt; Factorial&lt;12&gt;::val &lt;&lt; endl; // 479001600</p><p>} ///:~</p><empty-line/><p>That this program prints the correct value of <strong>12!</strong> is not alarming. What is alarming is that the computation is complete before the program even runs!<sup>.</sup></p><p>When the compiler attempts to instantiate <strong>Factorial&lt;12&gt;</strong>, it finds it must also instantiate <strong>Factorial&lt;11&gt;</strong>, which requires <strong>Factorial&lt;10&gt;</strong>, and so on. Eventually the recursion ends with the specialization <strong>Factorial&lt;1&gt;</strong>, and the computation unwinds. Eventually, <strong>Factorial&lt;12&gt;::val</strong> is replaced by the integral constant 479001600, and compilation ends. Since all the computation is done by the compiler, the values involved must be compile-time constants, hence the use of <strong>enum</strong>.<sup>[66]</sup> When the program runs, the only work left to do is print that constant followed by a newline. To convince yourself that a specialization of <strong>Factorial</strong> results in the correct compile-time value, you could use it as an array dimension, such as:<sup>.</sup></p><p>double nums[Factorial&lt;5&gt;::val];</p><p>assert(sizeof nums == sizeof(double)*120);</p><empty-line/></section><section><title><p>Compile-time programming</p></title><section><p>So what was meant to be a convenient way to perform type parameter substitution turned out to be a mechanism to support compile-time programming. Such a program is called a <strong>template metaprogram</strong> (since you’re in effect "programming a program"), and it turns out that you can do quite a lot with such a beast. In fact, template metaprogramming is <emphasis>Turing complete</emphasis> because it supports selection (if-else) and looping (through recursion); so theoretically you can perform any computation with it.<sup>[67]</sup> The factorial example above shows how to implement repetition; write a recursive template and provide a stopping criterion via a specialization. The following example shows how to compute Fibonacci numbers at compile time by the same technique<sup>.</sup></p><p>//: C05:Fibonacci.cpp</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><p>template&lt;int n&gt;</p><p>struct Fib {</p><p>   enum {val = Fib&lt;n-1&gt;::val + Fib&lt;n-2&gt;::val};</p><p>};</p><p>template&lt;&gt;</p><p>struct Fib&lt;1&gt; {</p><p>   enum {val = 1};</p><p>};</p><p>template&lt;&gt;</p><p>struct Fib&lt;0&gt; {</p><p>   enum {val = 0};</p><p>};</p><empty-line/><p>int main() {</p><p>   cout &lt;&lt; Fib&lt;5&gt;::val &lt;&lt; endl;   // 6</p><p>   cout &lt;&lt; Fib&lt;20&gt;::val &lt;&lt; endl;  // 6765</p><p>} ///:~<sup>.</sup></p><empty-line/><p>Fibonacci numbers are defined mathematically as:</p><p><image l:href="#5"/></p><p>The first two cases lead to the template specializations above, and the rule in the third line becomes the primary template<sup>.</sup></p></section><section><section><title><p>Compile-time looping</p></title><p>To compute any loop in a template metaprogram, it must first be reformulated recursively. For example, to raise the integer <strong>n</strong> to the power <strong>p</strong>, instead of using a loop such as in the following lines:<sup>.</sup></p><p>int val = 1;</p><p>while (p--)</p><p>  val *= n;</p><empty-line/><p>you would have to think of it as a recursive procedure:</p><p>int power(int n, int p) {</p><p>  return (p == 0) ? 1 : n*power(n, p - 1);</p><p>}</p><empty-line/><p>This can now be easily rendered as a template metaprogram as follows:</p><p>//: C05:Power.cpp</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;int N, int P&gt;</p><p>struct Power {</p><p>  enum {val = N * Power&lt;N, P-1&gt;::val};</p><p>};</p><p>template&lt;int N&gt;</p><p>struct Power&lt;N, 0&gt; {</p><p>  enum {val = 1};</p><p>};</p><p>int main() {</p><p>  cout &lt;&lt; Power&lt;2, 5&gt;::val &lt;&lt; endl;  // 32</p><p>} ///:~</p><empty-line/><p>Note that we need to use a partial specialization for the stopping condition, since the value <strong>N</strong> is still a free template parameter. This program only works for non-negative powers, of course<sup>.</sup></p><p>The following metaprogram adapted from Czarnecki and Eisenecker<sup>[68]</sup> is interesting in that it uses a template template parameter, and simulates passing a function as a parameter to another function, which "loops through" the numbers <strong>0..n</strong><sup><strong>.</strong></sup></p><p>//: C05:Accumulate.cpp</p><p>// Passes a "function" as a parameter at compile time</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><p>// Accumulates the results of F(0)..F(n)</p><p>template&lt;int n, template&lt;int&gt; class F&gt;</p><p>struct Accumulate {</p><p>   enum {val = Accumulate&lt;n-1, F&gt;::val + F&lt;n&gt;::val};</p><p>};</p><p>// The stopping criterion (returns the value F(0))</p><p>template&lt;template&lt;int&gt; class F&gt;</p><p>struct Accumulate&lt;0, F&gt; {</p><p>   enum {val = F&lt;0&gt;::val};</p><p>};</p><p>// Various "functions":</p><p>template&lt;int n&gt;</p><p>struct Identity {</p><p>   enum {val = n};</p><p>};</p><p>template&lt;int n&gt;</p><p>struct Square {</p><p>   enum {val = n*n};</p><p>};</p><p>template&lt;int n&gt;</p><p>struct Cube {</p><p>   enum {val = n*n*n};</p><p>};</p><p>int main() {</p><p>   cout &lt;&lt; Accumulate&lt;4, Identity&gt;::val &lt;&lt; endl; // 10</p><p>   cout &lt;&lt; Accumulate&lt;4, Square&gt;::val &lt;&lt; endl;   // 30</p><p>   cout &lt;&lt; Accumulate&lt;4, Cube&gt;::val &lt;&lt; endl;     // 100</p><p>} ///:~<sup>.</sup></p><empty-line/><p>The primary <strong>Accumulate</strong> template attempts to compute the sum <strong>F(n)+F(n&#x2011;1)…F(0)</strong>. The stopping criterion is obtained by a partial specialization, which "returns" <strong>F(0)</strong>. The parameter <strong>F</strong> is itself a template, and acts like a function as in the previous examples in this section. The templates <strong>Identity</strong>, <strong>Square</strong>, and <strong>Cube</strong> compute the corresponding functions of their template parameter that their names suggest. The first instantiation of <strong>Accumulate</strong> in <strong>main( )</strong> computes the sum 4+3+2+1+0, because the <strong>Identity</strong> function simply "returns" its template parameter. The second line in <strong>main( )</strong> adds the squares of those numbers (16+9+4+1+0), and the last computes the sum of the cubes (64+27+8+1+0)<sup>.</sup></p></section><section><title><p>Loop unrolling</p></title><p>Algorithm designers have always endeavored to optimize their programs. One time-honored optimization, especially for numeric programming, is loop unrolling, a technique that minimizes loop overhead. The quintessential loop-unrolling example is matrix multiplication. The following function multiplies a matrix and a vector. (The constants <strong>rows</strong> and <strong>cols</strong> have been previously defined.):<sup>.</sup></p><p>void mult(int a[rows][cols], int x[cols], int y[cols]) {</p><p>  for (int i = 0; i &lt; rows; ++i) {</p><p>      y[i] = 0;</p><p>      for (int j = 0; j &lt; cols; ++j)</p><p>        y[i] += a[i][j]*x[j];</p><p>  }</p><p>}</p><empty-line/><p>If <strong>cols</strong> is an even number, the overhead of incrementing and comparing the loop control variable <strong>j</strong> can be cut in half by "unrolling" the computation into pairs in the inner loop:<sup>.</sup></p><p>void mult(int a[rows][cols], int x[cols], int y[cols]) {</p><p>  for (int i = 0; i &lt; rows; ++i) {</p><p>      y[i] = 0;</p><p>      for (int j = 0; j &lt; cols; j += 2)</p><p>        y[i] += a[i][j]*x[j] + a[i][j+1]*x[j+1];</p><p>  }</p><p>}</p><empty-line/><p>In general, if <strong>cols</strong> is a factor of <strong>k</strong>, <strong>k</strong> operations can be performed each time the inner loop iterates, greatly reducing the overhead. The savings is only noticeable on large arrays, but that is precisely the case with industrial-strength mathematical computations<sup>.</sup></p><p>Function inlining also constitutes a form of loop unrolling. Consider the following approach to computing powers of integers.</p><p>//: C05:Unroll.cpp</p><p>// Unrolls an implicit loop via inlining</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;int n&gt;</p><p>inline int power(int m) {</p><p>   return power&lt;n-1&gt;(m) * m;</p><p>}</p><p>template&lt;&gt;</p><p>inline int power&lt;1&gt;(int m) {</p><p>   return m;</p><p>}</p><p>template&lt;&gt;</p><p>inline int power&lt;0&gt;(int m) {</p><p>   return 1;</p><p>}</p><p>int main()</p><p>{</p><p>   int m = 4;</p><p>   cout &lt;&lt; power&lt;3&gt;(m) &lt;&lt; endl;</p><p>} ///:~<sup>.</sup></p><empty-line/><p>Conceptually, the compiler must generate three specializations of <strong>power&lt;&gt;</strong>, one each for the template parameters 3, 2, and 1. Because the code for each of these functions can be inlined, the actual code that is inserted into <strong>main( )</strong> is the single expression <strong>m*m*m</strong>. Thus, a simple template specialization coupled with inlining here provides a way to totally avoid loop control overhead.<sup>[69]</sup> This approach to loop unrolling is limited by your compiler’s inlining depth, of course<sup>.</sup></p></section><section><title><p>Compile-time selection</p></title><p>To simulate conditionals at compile time, you can use the conditional ternary operator in an <strong>enum</strong> declaration. The following program uses this technique to calculate the maximum of two integers at compile time<sup>.</sup></p><p>//: C05:Max.cpp</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;int n1, int n2&gt;</p><p>struct Max {</p><p>   enum {val = n1 &gt; n2 ? n1 : n2};</p><p>};</p><p>int main() {</p><p>   cout &lt;&lt; Max&lt;10, 20&gt;::val &lt;&lt; endl;  // 20</p><p>} ///:~</p><empty-line/><p>If you want to use compile-time conditions to govern custom code generation, you can once again use specializations of the values <strong>true</strong> and <strong>false</strong>:</p><p>//: C05:Conditionals.cpp</p><p>// Uses compile-time conditions to choose code</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;bool cond&gt;</p><p>struct Select {};</p><empty-line/><p>template&lt;&gt;</p><p>struct Select&lt;true&gt; {</p><p>  static inline void f() { statement1(); }</p><p>private:</p><p>  static inline void statement1() {</p><p>    cout &lt;&lt; "This is";</p><p>    cout &lt;&lt; " statement1 executing\n";</p><p>  }</p><p>};</p><p>template&lt;&gt;</p><p>struct Select&lt;false&gt; {</p><p>  static inline void f() { statement2(); }</p><p>private:</p><p>  static inline void statement2() {</p><p>    cout &lt;&lt; "This is";</p><p>    cout &lt;&lt; " statement2 executing\n";</p><p>  }</p><p>};</p><p>template&lt;bool cond&gt;</p><p>void execute() {</p><p>  Select&lt;cond&gt;::f();</p><p>}</p><empty-line/><p>int main() {</p><p>  execute&lt;sizeof(int) == 4&gt;();</p><p>} ///:~<sup>.</sup></p><empty-line/><p>This program is the equivalent of the expression:</p><p>if (cond)</p><p>  statement1();</p><p>else</p><p>  statement2();</p><empty-line/><p>except that the condition <strong>cond</strong> is evaluated at compile time, and the appropriate versions of <strong>execute&lt;&gt;( )</strong> and <strong>Select&lt;&gt;</strong> are instantiated by the compiler. The function <strong>Select&lt;&gt;::f( )</strong> executes at runtime, of course. A <strong>switch</strong> statement can be emulated in similar fashion, but specializing on each case value instead of the values <strong>true</strong> and <strong>false</strong><sup><strong>.</strong></sup></p></section><section><title><p>Compile-time assertions</p></title><p>In Chapter 2 we touted the virtues of using assertions as part of an overall defensive programming strategy. An assertion is basically an evaluation of a Boolean expression followed by a suitable action: do nothing if the condition is true, or halt with a diagnostic message otherwise. The previous section showed how to evaluate compile-time Boolean expressions. The remaining challenge in emulating assertions at compile time is to print a meaningful error message and halt. All that is required to halt the compiler is a compile error; the trick is to insert helpful text in the error message. The following example of Alexandrescu<sup>[70]</sup> uses template specialization, a local class, and a little macro magic to do the job<sup>.</sup></p><p>//: C05:StaticAssert.cpp</p><p>//{-g++}</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>// A template and a specialization</p><p>template&lt;bool&gt;</p><p>struct StaticCheck {</p><p>   StaticCheck(...);</p><p>};</p><p>template&lt;&gt;</p><p>struct StaticCheck&lt;false&gt;{};</p><empty-line/><p>// The macro (generates a local class)</p><p>#define STATIC_CHECK(expr, msg) {              \</p><p>   class Error_##msg{};         \</p><p>   sizeof((StaticCheck&lt;expr&gt;(Error_##msg()))); \</p><p>}</p><empty-line/><p>// Detects narrowing conversions</p><p>template&lt;class To, class From&gt;</p><p>To safe_cast(From from) {</p><p>   STATIC_CHECK(sizeof(From) &lt;= sizeof(To),</p><p> NarrowingConversion);</p><p>   return reinterpret_cast&lt;To&gt;(from);</p><p>}</p><empty-line/><p>int main() {</p><p>   void* p = 0;</p><p>   int i = safe_cast&lt;int&gt;(p);</p><p>   cout &lt;&lt; "int cast okay\n";</p><p>//!   char c = safe_cast&lt;char&gt;(p);</p><p>} ///:~<sup>.</sup></p><empty-line/><p>This example defines a function template, <strong>safe_cast&lt;&gt;( )</strong>, that checks to see if the object it is casting from is no larger than the type of object it casts to. If the size of the target object type is smaller, then the user will be notified at compile time that a narrowing conversion was attempted. Notice that the <strong>StaticCheck</strong> class template has the curious feature that <emphasis>anything</emphasis> can be converted to an instance of <strong>StaticCheck&lt;true&gt;</strong> (because of the ellipsis in its constructor<sup>[71]</sup>), and <emphasis>nothing</emphasis> can be converted to a <strong>StaticCheck&lt;false&gt;</strong>, because no conversions are supplied for that specialization. The idea is to attempt to create an instance of a new class and attempt to convert it to <strong>StaticCheck&lt;true&gt;</strong><emphasis>at compile time</emphasis> whenever the condition of interest is true, or to a <strong>StaticCheck&lt;false&gt;</strong> object when the condition being tested is false. Since the <strong>sizeof</strong> operator does its work at compile time, it is used to attempt the conversion. If the condition is false, the compiler will complain that it doesn’t know how to convert from the new class type to <strong>StaticCheck&lt;false&gt;</strong>. (The extra parentheses inside the <strong>sizeof</strong> invocation in <strong>STATIC_CHECK( )</strong> are to prevent the compiler from thinking that we’re trying to invoke <strong>sizeof</strong> on a function, which is illegal.) To get some meaningful information inserted into the error message, the new class name carries key text in its name<sup>.</sup></p><p>The best way to understand this technique is to walk through a specific case. Consider the line in <strong>main( )</strong> above which reads:</p><p>   int i = safe_cast&lt;int&gt;(p);</p><empty-line/><p>The call to <strong>safe_cast&lt;int&gt;(p)</strong> contains the following macro expansion replacing its first line of code:</p><p>{                                    \</p><p>   class Error_NarrowingConversion{};               \</p><p>   sizeof(StaticCheck&lt;sizeof(void*) &lt;= sizeof(int)&gt; \</p><p>           (Error_NarrowingConversion()));          \</p><p>}</p><empty-line/><p>(Recall that the token-pasting preprocessing operator, <strong>##</strong>, concatenates its operand into a single token, so <strong>Error_##NarrowingConversion</strong> becomes the token <strong>Error_NarrowingConversion</strong> after preprocessing). The class <strong>Error_NarrowingConversion</strong> is a <emphasis>local class</emphasis> (meaning that it is declared inside a non-namespace scope) because it is not needed elsewhere in the program. The application of the <strong>sizeof</strong> operator here attempts to determine the size of an instance of <strong>StaticCheck&lt;true&gt;</strong> (because <strong>sizeof(void*) &lt;= sizeof(int)</strong> is true on our platforms), created implicitly from the temporary object returned by the call <strong>Error_NarrowingConversion( )</strong>. The compiler knows the size of the new class <strong>Error_NarrowingConversion</strong> (it’s empty), and so the compile-time use of <strong>sizeof</strong> at the outer level in <strong>STATIC_CHECK( )</strong> is valid. Since the conversion from the <strong>Error_NarrowingConversion</strong> temporary to <strong>StaticCheck&lt;true&gt;</strong> succeeds, so does this outer application of <strong>sizeof</strong>, and execution continues<sup>.</sup></p><p>Now consider what would happen if the comment were removed from the last line of <strong>main( )</strong>:</p><p>   char c = safe_cast&lt;char&gt;(p);</p><empty-line/><p>In this case the <strong>STATIC_CHECK( )</strong> macro inside <strong>safe_cast&lt;char&gt;(p)</strong> expands to:</p><p>{                                     \</p><p>   class Error_NarrowingConversion{}; \</p><p>   sizeof(StaticCheck&lt;sizeof(void*) &lt;= sizeof(char)&gt; \</p><p>           (Error_NarrowingConversion()));           \</p><p>}</p><empty-line/><p>Since the expression <strong>sizeof(void*) &lt;= sizeof(char)</strong> is false, a conversion from an <strong>Error_NarrowingConversion</strong> temporary to <strong>StaticCheck&lt;false&gt;</strong> is attempted, as follows:</p><p>sizeof(StaticCheck&lt;false&gt;(Error_NarrowingConversion()));</p><empty-line/><p>which fails, so the compiler halts with a message something like the following:<sup>.</sup></p><p>Cannot cast from 'Error_NarrowingConversion' to 'StaticCheck&lt;0&gt;' in function</p><p>char safe_cast&lt;char,void *&gt;(void *)</p><empty-line/><p>The class name <strong>Error_NarrowingConversion</strong> is the meaningful message judiciously arrange by the coder. In general, to perform a static assertion with this technique, you just invoke the <strong>STATIC_CHECK</strong> macro with the compile-time condition to check and with a meaningful name to describe the error<sup>.</sup></p></section></section></section><section><title><p>Expression templates</p></title><p>Perhaps the most powerful application of templates is a technique discovered independently in 1994 by Todd Veldhuizen<sup>[72]</sup> and David Vandevoorde:<sup>[73]</sup><emphasis>expression templates</emphasis>. Expression templates enable extensive compile-time optimization of certain computations that results in code that is at least as fast as hand-optimized Fortran, and yet preserves the natural notation of mathematics via operator overloading. Although you wouldn’t be likely to use this technique in everyday programming, it is the basis for a number of sophisticated, high-performance mathematical libraries written in C++.<sup>[74]</sup></p><p>To motivate the need for expression templates, consider typical numerical linear algebra operations, such as adding together two matrices or vectors,<sup>[75]</sup> such as in the following:</p><p>D = A + B + C;</p><empty-line/><p>In naive implementations, this expression would result in a number of temporaries—one for <strong>A+B</strong>, and one for (<strong>A+B)+C</strong>. When these variables represent immense matrices or vectors, the coincident drain on resources is unacceptable. Expression templates allow you to use the same expression without temporaries<sup>.</sup></p><p>In the following sample program, we define a <strong>MyVector</strong> class to simulate mathematical vectors of any size. We use a non-type template argument for the length of the vector. We also define a <strong>MyVectorSum</strong> class to act as a proxy class for a sum of <strong>MyVector</strong> objects. This allows us to use lazy evaluation, so the addition of vector components is performed on demand without the need for temporaries<sup>.</sup></p><p>//: C05:MyVector.cpp</p><p>// Optimizes away temporaries via templates</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>// A proxy class for sums of vectors</p><p>template&lt;class, size_t&gt; class MyVectorSum;</p><empty-line/><p>template&lt;class T, size_t N&gt;</p><p>class MyVector {</p><p>  T data[N];</p><p>public:</p><p>  MyVector&lt;T,N&gt;&amp; operator=(const MyVector&lt;T,N&gt;&amp; right) {</p><p>    for (size_t i = 0; i &lt; N; ++i)</p><p>      data[i] = right.data[i];</p><p>    return *this;</p><p>  }</p><p>  MyVector&lt;T,N&gt;&amp; operator=(const MyVectorSum&lt;T,N&gt;&amp; right);</p><p>  const T&amp; operator[](size_t i) const {</p><p>    return data[i];</p><p>  }</p><p>  T&amp; operator[](size_t i) {</p><p>    return data[i];</p><p>  }</p><p>};</p><p>// Proxy class hold references; uses lazy addition</p><p>template &lt;class T, size_t N&gt;</p><p>class MyVectorSum {</p><p>  const MyVector&lt;T,N&gt;&amp; left;</p><p>  const MyVector&lt;T,N&gt;&amp; right;</p><p>public:</p><p>  MyVectorSum(const MyVector&lt;T,N&gt;&amp; lhs,</p><p>              const MyVector&lt;T,N&gt;&amp; rhs)</p><p>      : left(lhs), right(rhs) {}</p><p>  T operator[](size_t i) const {</p><p>    return left[i] + right[i];</p><p>  }</p><p>};</p><p>// Operator to support v3 = v1 + v2</p><p>template&lt;class T, size_t N&gt;</p><p>MyVector&lt;T,N&gt;&amp;</p><p>MyVector&lt;T,N&gt;::operator=(const MyVectorSum&lt;T,N&gt;&amp; right) {</p><p>  for (size_t i = 0; i &lt; N; ++i)</p><p>    data[i] = right[i];</p><p>  return *this;</p><p>}</p><p>// operator+ just stores references</p><p>template&lt;class T, size_t N&gt;</p><p>inline MyVectorSum&lt;T,N&gt;</p><p>operator+(const MyVector&lt;T,N&gt;&amp; left,</p><p>          const MyVector&lt;T,N&gt;&amp; right) {</p><p>  return MyVectorSum&lt;T,N&gt;(left, right);</p><p>}</p><p>// Convenience functions for the test program below</p><p>template&lt;class T, size_t N&gt;</p><p>void init(MyVector&lt;T,N&gt;&amp; v) {</p><p>  for (size_t i = 0; i &lt; N; ++i)</p><p>    v[i] = rand() % 100;</p><p>}</p><p>template&lt;class T, size_t N&gt;</p><p>void print(MyVector&lt;T,N&gt;&amp; v) {</p><p>  for (size_t i = 0; i &lt; N; ++i)</p><p>    cout &lt;&lt; v[i] &lt;&lt; ' ';</p><p>  cout &lt;&lt; endl;</p><p>}</p><p>int main() {</p><p>  MyVector&lt;int, 5&gt; v1;</p><p>  init(v1);</p><p>  print(v1);</p><p>  MyVector&lt;int, 5&gt; v2;</p><p>  init(v2);</p><p>  print(v2);</p><p>  MyVector&lt;int, 5&gt; v3;</p><p>  v3 = v1 + v2;</p><p>  print(v3);</p><p>  MyVector&lt;int, 5&gt; v4;</p><p>  // Not yet supported:</p><p>//!  v4 = v1 + v2 + v3;</p><p>} ///:~<sup>.</sup></p><empty-line/><p>The <strong>MyVectorSum</strong> class does no computation when it is created; it merely holds references to the two vectors to be added. It is only when you access a component of a vector sum that it is calculated (see its <strong>operator[]( )</strong>). The overload of the assignment operator for <strong>MyVector</strong> that takes a <strong>MyVectorSum</strong> argument is for an expression such as:<sup>.</sup></p><p>v1 = v2 + v3;  // add two vectors</p><empty-line/><p>When the expression <strong>v1+v2</strong> is evaluated, a <strong>MyVectorSum</strong> object is returned (or actually, inserted inline, since that <strong>operator+( )</strong> is declared <strong>inline</strong>). This is a small, fixed-size object (it holds only two references). Then the assignment operator mentioned above is invoked:</p><p>v3.operator=&lt;int,5&gt;(MyVectorSum&lt;int,5&gt;(v2, v3));</p><empty-line/><p>This assigns to each element of <strong>v3</strong> the sum of the corresponding elements of <strong>v1</strong> and <strong>v2</strong>, computed in real time. No temporary <strong>MyVector</strong> objects are created.</p><p>This program does not support an expression that has more than two operands, however, such as</p><p>v4 = v1 + v2 + v3;</p><empty-line/><p>The reason is that after the first addition, a second addition is attempted:</p><p>(v1 + v2) <strong>+</strong> v3;</p><empty-line/><p>which would require an <strong>operator+( )</strong> with a first argument of <strong>MyVectorSum</strong> and a second argument of type <strong>MyVector</strong>. We could attempt to provide a number of overloads to meet all situations, but it is better to let templates do the work, as in the following version of the program<sup>.</sup></p><p>//: C05:MyVector2.cpp</p><p>// Handles sums of any length with expression templates</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>// A proxy class for sums of vectors</p><p>template&lt;class, size_t, class, class&gt; class MyVectorSum;</p><empty-line/><p>template&lt;class T, size_t N&gt;</p><p>class MyVector {</p><p>  T data[N];</p><p>public:</p><p>  MyVector&lt;T,N&gt;&amp; operator=(const MyVector&lt;T,N&gt;&amp; right) {</p><p>    for (size_t i = 0; i &lt; N; ++i)</p><p>      data[i] = right.data[i];</p><p>    return *this;</p><p>  }</p><p>  template&lt;class Left, class Right&gt;</p><p>  MyVector&lt;T,N&gt;&amp;</p><p>    operator=(const MyVectorSum&lt;T,N,Left,Right&gt;&amp; right);</p><p>  const T&amp; operator[](size_t i) const {</p><p>    return data[i];</p><p>  }</p><p>  T&amp; operator[](size_t i) {</p><p>    return data[i];</p><p>  }</p><p>};</p><p>// Allows mixing MyVector and MyVectorSum</p><p>template &lt;class T, size_t N, class Left, class Right&gt;</p><p>class MyVectorSum {</p><p>  const Left&amp; left;</p><p>  const Right&amp; right;</p><p>public:</p><p>  MyVectorSum(const Left&amp; lhs, const Right&amp; rhs)</p><p>      : left(lhs), right(rhs) {}</p><p>  T operator[](size_t i) const {</p><p>    return left[i] + right[i];</p><p>  }</p><p>};</p><p>template&lt;class T, size_t N&gt;</p><p>template&lt;class Left, class Right&gt;</p><p>MyVector&lt;T,N&gt;&amp;</p><p>MyVector&lt;T,N&gt;::</p><p>operator=(const MyVectorSum&lt;T,N,Left,Right&gt;&amp; right) {</p><p>  for (size_t i = 0; i &lt; N; ++i)</p><p>    data[i] = right[i];</p><p>  return *this;</p><p>}</p><p>// operator+ just stores references</p><p>template&lt;class T, size_t N&gt;</p><p>inline MyVectorSum&lt;T,N,MyVector&lt;T,N&gt;,MyVector&lt;T,N&gt; &gt;</p><p>operator+(const MyVector&lt;T,N&gt;&amp; left,</p><p>          const MyVector&lt;T,N&gt;&amp; right) {</p><p>  return</p><p>    MyVectorSum&lt;T,N,MyVector&lt;T,N&gt;,MyVector&lt;T,N&gt; &gt;</p><p>      (left,right);</p><p>}</p><empty-line/><p>template&lt;class T, size_t N, class Left, class Right&gt;</p><p>inline</p><p>MyVectorSum&lt;T, N, MyVectorSum&lt;T,N,Left,Right&gt;,</p><p>            MyVector&lt;T,N&gt; &gt;</p><p>operator+(const MyVectorSum&lt;T,N,Left,Right&gt;&amp; left,</p><p>          const MyVector&lt;T,N&gt;&amp; right) {</p><p>  return MyVectorSum&lt;T,N,MyVectorSum&lt;T,N,Left,Right&gt;,</p><p>          MyVector&lt;T,N&gt; &gt;</p><p>    (left, right);</p><p>}</p><p>// Convenience functions for the test program below</p><p>template&lt;class T, size_t N&gt;</p><p>void init(MyVector&lt;T,N&gt;&amp; v) {</p><p>  for (size_t i = 0; i &lt; N; ++i)</p><p>    v[i] = rand() % 100;</p><p>}</p><p>template&lt;class T, size_t N&gt;</p><p>void print(MyVector&lt;T,N&gt;&amp; v) {</p><p>  for (size_t i = 0; i &lt; N; ++i)</p><p>    cout &lt;&lt; v[i] &lt;&lt; ' ';</p><p>  cout &lt;&lt; endl;</p><p>}</p><p>int main() {</p><p>  MyVector&lt;int, 5&gt; v1;</p><p>  init(v1);</p><p>  print(v1);</p><p>  MyVector&lt;int, 5&gt; v2;</p><p>  init(v2);</p><p>  print(v2);</p><p>  MyVector&lt;int, 5&gt; v3;</p><p>  v3 = v1 + v2;</p><p>  print(v3);</p><p>  // Now supported:</p><p>  MyVector&lt;int, 5&gt; v4;</p><p>  v4 = v1 + v2 + v3;</p><p>  print(v4);</p><p>  MyVector&lt;int, 5&gt; v5;</p><p>  v5 = v1 + v2 + v3 + v4;</p><p>  print(v5);</p><p>} ///:~<sup>.</sup></p><empty-line/><p>Instead of committing ahead of time which types the arguments of a sum will be, we let the template facility deduce them with the template arguments, <strong>Left</strong> and <strong>Right</strong>. The <strong>MyVectorSum</strong> template takes these extra two parameters so it can represent a sum of any combination of pairs of <strong>MyVector</strong> and <strong>MyVectorSum</strong>. Note also that the assignment operator this time is a member function template. This also allows any &lt;<strong>T, N&gt;</strong> pair to be coupled with any &lt;<strong>Left, Right&gt;</strong> pair, so a <strong>MyVector</strong> object can be assigned from a <strong>MyVectorSum</strong> holding references to any possible pair of the types <strong>MyVector</strong> and <strong>MyVectorSum</strong>. As we did before, let’s trace through a sample assignment to understand exactly what takes place, beginning with the expression<sup>.</sup></p><p>v4 = v1 + v2 + v3;</p><empty-line/><p>Since the resulting expressions become quite unwieldy, in the explanation that follows, we will use <strong>MVS</strong> as shorthand for <strong>MyVectorSum</strong>, and will omit the template arguments<sup>.</sup></p><p>The first operation is <strong>v1+v2</strong>, which invokes the inline <strong>operator+( )</strong>, which in turn inserts <strong>MVS(v1, v2)</strong> into the compilation stream. This is then added to <strong>v3</strong>, which results in a temporary object according to the expression <strong>MVS(MVS(v1, v2), v3)</strong>. The final representation of the entire statement is<sup>.</sup></p><p>v4.operator+(MVS(MVS(v1, v2), v3));</p><empty-line/><p>This transformation is all arranged by the compiler and explains why this technique carries the moniker "expression templates"; the template <strong>MyVectorSum</strong> represents an expression (an addition, in this case), and the nested calls above are reminiscent of the parse tree of the left-associative expression <strong>v1+v2+v3</strong><sup><strong>.</strong></sup></p><p>An excellent article by Angelika Langer and Klaus Kreft explains how this technique can be extended to more complex computations.<sup>[76]</sup></p></section></section><section><title><p>Template compilation models</p></title><section><p>You have certainly noticed by now that all our template examples place fully-defined templates within each compilation unit. (For example, we place them completely within single-file programs or in header files for multi-file programs.) This runs counter to the conventional practice of separating ordinary function definitions from their declarations by placing the latter in header files and the function implementations in separate (that is, <strong>.cpp</strong>) files. Everyone knows the reason for this separation: non-inline function bodies in header files can lead to multiple function definitions, which results in a linker error. A nice side benefit of this approach is that vendors can distribute pre-compiled code along with headers so that users cannot see their function implementations, and compile times are shorter since header files are smaller<sup>.</sup></p></section><section><title><p>The inclusion model</p></title><p>Templates, on the other hand, are not code, per se, but instructions for code generation; only template instantiations are real code. When a compiler has seen a complete template definition during a compilation and then encounters a point of instantiation for that template in the same translation unit, it must deal with the fact that an equivalent point of instantiation may be present in another translation unit. The most common approach consists in generating the code for the instantiation in every translation unit and let the linker weed out duplicates. That particular approach also works well with inline functions that cannot be inlined and with virtual function tables, which is one of the reasons for its popularity. Nonetheless, several compilers prefer instead to rely on more complex schemes to avoid generating a particular instantiation more than once. Either way, it is the responsibility of the C++ translation system to avoid errors due to multiple equivalent points of instantiation<sup>.</sup></p><p>A drawback of this approach is obviously that all template source code is visible to the client. If you want to know exactly how your standard library is implemented, all you have to do is inspect the headers in your installation. There is little opportunity for library vendors to hide their implementation strategies. Another noticeable disadvantage of the inclusion model is that header files are much, much larger than they would be if function bodies were compiled separately. This can increase compile times dramatically over traditional compilation models<sup>.</sup></p><p>To help reduce the large headers required by the inclusion model, C++ offers two (non-exclusive) alternative code organization mechanisms: you can manually instantiate each specialization using <emphasis>explicit instantiation</emphasis> or you can use <emphasis>exported templates</emphasis>, which actually support a large degree of separate compilation<sup>.</sup></p></section><section><title><p>Explicit instantiation</p></title><p>You can manually direct the compiler to instantiate any template specializations of your choice. When you use this technique, there must be one and only one such directive for each such specialization; otherwise you might get multiple definition errors, just as you would with ordinary, non-inline functions with identical signatures. To illustrate, we first (erroneously) separate the declaration of the <strong>min</strong> template from earlier in this chapter from its definition, following the normal pattern for ordinary, non-inline functions. The following example consists of five files:<sup>.</sup></p><p>·         <strong>OurMin.h</strong>: contains the declaration of the <strong>min</strong> function template.</p><p>·         <strong>OurMin</strong>.<strong>cpp</strong>: contains the definition of the <strong>min</strong> function template.</p><p>·         <strong>UseMin1.cpp</strong>: attempts to use an <strong>int</strong>-instantiation of <strong>min</strong></p><p>·         <strong>UseMin2.cpp</strong>: attempts to use a <strong>double</strong>-instantiation of <strong>min</strong></p><p>·         <strong>MinMain.cpp</strong>: calls <strong>usemin1( )</strong> and <strong>usemin2( )</strong></p><p>Here are the files:</p><p>//: C05:OurMin.h</p><p>#ifndef OURMIN_H</p><p>#define OURMIN_H</p><p>// The declaration of min</p><p>template&lt;typename T&gt; const T&amp; min(const T&amp;, const T&amp;);</p><empty-line/><p>#endif ///:~</p><empty-line/><p>// OurMin.cpp</p><p>#include "OurMin.h"</p><p>// The definition of min</p><p>template&lt;typename T&gt; const T&amp; min(const T&amp; a, const T&amp; b) {</p><p>  return (a &lt; b) ? a : b;</p><p>}</p><empty-line/><p>//: C05:UseMin1.cpp {O}</p><p>#include &lt;iostream&gt;</p><p>#include "OurMin.h"</p><p>void usemin1() {</p><p>  std::cout &lt;&lt; min(1,2) &lt;&lt; std::endl;</p><p>} ///:~</p><empty-line/><p>//: C05:UseMin2.cpp {O}</p><p>#include &lt;iostream&gt;</p><p>#include "OurMin.h"</p><p>void usemin2() {</p><p>  std::cout &lt;&lt; min(3.1,4.2) &lt;&lt; std::endl;</p><p>} ///:~</p><empty-line/><p>//: C05:MinMain.cpp</p><p>//{L} UseMin1 UseMin2 MinInstances</p><p>void usemin1();</p><p>void usemin2();</p><empty-line/><p>int main() {</p><p>  usemin1();</p><p>  usemin2();</p><p>} ///:~</p><empty-line/><p>When we attempt to build this program, the linker reports unresolved external references for <strong>min&lt;int&gt;( )</strong> and <strong>min&lt;double&gt;( )</strong>. The reason is that when the compiler encounters the calls to specializations of <strong>min</strong> in <strong>UseMin1</strong> and <strong>UseMin2</strong>, only the declaration of <strong>min</strong> is visible. Since the definition is not available, the compiler assumes it will come from some other translation unit, and the needed specializations are therefore not instantiated at that point, leaving the linker to eventually complain that it cannot find them<sup>.</sup></p><p>To solve this problem, we will introduce a new file, <strong>MinInstances.cpp</strong>, that explicitly instantiates the needed specializations of <strong>min</strong>:</p><p>//: C05:MinInstances.cpp {O}</p><p>#include "OurMin.cpp"</p><p>// Explicit Instantiations for int and double</p><p>template const int&amp; min&lt;int&gt;(const int&amp;, const int&amp;);</p><p>template const double&amp; min&lt;double&gt;(const double&amp;,</p><p>                    const double&amp;);</p><p>///:~</p><empty-line/><p>To manually instantiate a particular template specialization, you precede the specialization’s declaration with the <strong>template</strong> keyword. That’s it! Note that we must include <strong>OurMin.cpp</strong>, not <strong>OurMin.h</strong>, here, because the compiler needs the template definition to perform the instantiation. This is the only place where we have to do this in this program,<sup>[77]</sup> however, since it gives us the unique instantiations of <strong>min</strong> that we need; the declarations alone suffice for the other files. Since we are including <strong>OurMin.cpp</strong> with the macro preprocessor, we add include guards:<sup>.</sup></p><p>//: C05:OurMin.cpp {O}</p><p>#ifndef OURMIN_CPP</p><p>#define OURMIN_CPP</p><p>#include "OurMin.h"</p><empty-line/><p>template&lt;typename T&gt; const T&amp; min(const T&amp; a, const T&amp; b) {</p><p>  return (a &lt; b) ? a : b;</p><p>}</p><p>#endif ///:~</p><empty-line/><p>Now when we compile all the files together into a complete program, the unique instances of <strong>min</strong> are found, and the program executes correctly, giving the output:</p><p>1</p><p>3.1</p><empty-line/><p>You can also manually instantiate classes and static data members. When explicitly instantiating a class, all member functions for the requested specialization are instantiated, except any that may have been explicitly instantiated previously. Using only implicit instantiation has the advantage here: only member functions that actually get called are instantiated. Explicit instantiation is intended for large projects in which a hefty chunk of compilation time can be avoided. Whether you use implicit or explicit instantiation is independent of which template compilation you use, of course; you can use manual instantiation with either the inclusion model or the separation model (discussed in the next section)<sup>.</sup></p></section><section><title><p>The separation model</p></title><p>The separation model of template compilation allows you to separate function template definitions or static data member definitions from their declarations across translation units, just like you do with ordinary functions and data, by <emphasis>exporting</emphasis> templates. After reading the preceding two sections, this must sound strange indeed. Why bother to have the inclusion model in the first place if you can just adhere to the status quo? The reasons are both historical and technical<sup>.</sup></p><p>Historically, the inclusion model was the first to experience widespread commercial use. Part of the reason for that was that the separation model was not well specified until late in the standardization process. It turns out that the inclusion model is the easier of the two to implement. All C++ compilers support the inclusion model. A lot of working code was in existence long before the semantics of the separation model were finalized<sup>.</sup></p><p>The technical aspect reflects the fact that the separation model is difficult to implement. In fact, as of summer 2003 only one compiler front end (EDG) supports the separation model, and at the moment it still requires that template source code be available at compile time to perform instantiation on demand. Plans are in place to use some form of intermediate code instead of requiring that the original source be at hand, at which point you will be able to ship "pre-compiled" templates without shipping source code. Because of the lookup complexities explained earlier in this chapter (about dependent names being looked up in the template definition context), a full template definition still has to be available in some form when you compile a program that instantiates it<sup>.</sup></p><p>The syntax to separate the source code of a template definition from its declaration is easy enough. You use the <strong>export</strong> keyword:</p><p>// C05:OurMin2.h</p><p>// Declares min as an exported template</p><p>//! (Only works with EDG-based compilers)</p><p>#ifndef OURMIN2_H</p><p>#define OURMIN2_H</p><p>export template&lt;typename T&gt; const T&amp; min(const T&amp;,</p><p>                          const T&amp;);</p><p>#endif</p><empty-line/><p>Similar to <strong>inline</strong> or <strong>virtual</strong>, the <strong>export</strong> keyword need only be mentioned once in a compilation stream, where an exported template is introduced. For this reason, we need not repeat it in the implementation file, but it is considered good practice to do so:<sup>.</sup></p><p>// C05:OurMin2.cpp</p><p>// The definition of the exported min template</p><p>//! (Only works with EDG-based compilers)</p><p>#include "OurMin2.h"</p><p>export</p><p>template&lt;typename T&gt; const T&amp; min(const T&amp; a, const T&amp; b) {</p><p>  return (a &lt; b) ? a : b;</p><p>} ///:~</p><empty-line/><p>The <strong>UseMin</strong> files used previously only need to be updated to include the correct header file (<strong>OurMin2.h</strong>), and the main program need not change at all. Although this appears to give true separation, the file with the template definition (<strong>OurMin2.cpp</strong>) must still be shipped to users (because it must be processed for each instantiation of <strong>min</strong>) until such time as some form of intermediate code representation of template definitions is supported. So while the standard does provide for a true separation model, not all of its benefits can be reaped today. Only one family of compilers currently support export (those based on the EDG front end), and these compilers currently do not exploit the potential ability to distribute template definitions in compiled form<sup>.</sup></p></section></section><section><title><p>Summary</p></title><p>Templates have gone far beyond simple type parameterization! When you combine argument type deduction, custom specialization, and template metaprogramming, C++ templates emerge as a powerful code generation mechanism.</p><p>One of the weaknesses of C++ templates we skipped in this chapter is the difficulty in interpreting compile-time error messages. When you’re not used to it, the quantity of inscrutable text spewed out by the compiler is quite overwhelming. If it’s any consolation, C++ compilers have actually gotten a lot better about this. Leor Zolman has written a nifty tool <strong>STLFilt</strong>, that renders these error messages much more readable by extracting the useful information and throwing away the rest.<sup>[78]</sup></p><p>Another important idea to take away from this chapter is that <emphasis>a template implies an interface</emphasis>. That is, even though the <strong>template</strong> keyword says "I’ll take any type," the code in a template definition actually requires that certain operators and member functions be supported—that’s the interface. So in reality, a template definition is saying, "I’ll take any type that supports this interface." Things would be much nicer if the compiler could simply say, "Hey, this type that you’re trying to instantiate the template with doesn’t support that interface—can’t do it." Using templates, therefore, constitutes a sort of "latent type checking" that is more flexible than the pure object-oriented practice of requiring all types to derive from certain base classes<sup>.</sup></p><p>In Chapters 6 and 7 we explore in depth the most famous application of templates, the subset of the standard C++ library commonly known as the Standard Template Library (STL). Chapters 9 and 10 also use template techniques not found in this chapter<sup>.</sup></p></section><section><title><p>Exercises</p></title><p>             1.             Write a unary function template that takes a single type template parameter. Create a full specialization for the type <strong>int</strong>. Also create a non-template overload for this function that takes a single <strong>int</strong> parameter. Have your main program invoke three function variations.</p><p>             2.             Write a class template that uses a vector to implement a stack data structure.</p><p>        38.             Modify your solution to the previous exercise so that the type of the container used to implement the stack is a template template parameter.</p><p>        39.             In the following code, the class <strong>NonComparable</strong> does not have an <strong>operator=( )</strong>. Why would the presence of the class <strong>HardLogic</strong> cause a compile error, but <strong>SoftLogic</strong> would not?</p><p>class Noncomparable {};</p><p>struct HardLogic {</p><p>  Noncomparable nc1, nc2;</p><p>  void compare() {</p><p>     return nc1 == nc2; // Compiler error</p><p>  }</p><p>};</p><p>template&lt;class T&gt;</p><p>struct SoftLogic {</p><p>  Noncomparable nc1, nc2;</p><p>  void noOp() {}</p><p>  void compare() {</p><p>    nc1 == nc2;</p><p>  }</p><p>};</p><p>int main() {</p><p>  SoftLogic&lt;Noncomparable&gt; l;</p><p>  l.noOp(); }</p><empty-line/><p>        40.             Write a function template that takes a single type parameter (<strong>T</strong>) and accepts four function arguments: an array of <strong>T</strong>, a start index, a stop index (inclusive), and an optional initial value. The function returns the sum of all the array elements in the specified range. Use the default constructor of <strong>T</strong> for the default initial value.</p><p>         41.             Repeat the previous exercise but use explicit instantiation to manually create specializations for <strong>int</strong> and <strong>double</strong>, following the technique explained in this chapter.</p><p>        42.             Why does the following code not compile? (Hint: what do class member functions have access to?)</p><empty-line/><p>class Buddy {};</p><p>template&lt;class T&gt;</p><p>class My {</p><p>  int i;</p><p>public:</p><p>  void play(My&lt;Buddy&gt;&amp; s) {</p><p>    s.i = 3;</p><p>  }</p><p>};</p><p>int main() {</p><p>  My&lt;int&gt; h;</p><p>  My&lt;Buddy&gt; me, bud;</p><p>  h.play(bud);</p><p>  me.play(bud);</p><p>}</p><empty-line/><p>        43.             Why does the following code not compile?</p><empty-line/><p>template&lt;class T&gt;</p><p>double pythag(T a, T b, T c) {</p><p>  return (-b + sqrt(double(b*b - 4*a*c))) / 2*a;</p><p>}</p><p>int main() {</p><p>  pythag(1, 2, 3);</p><p>  pythag(1.0, 2.0, 3.0);</p><p>  pythag(1, 2.0, 3.0);</p><p>  pythag&lt;double&gt;(1, 2.0, 3.0);</p><p>}</p><empty-line/><p>        44.             Write templates that take non-type parameters of the following variety: an <strong>int</strong>, a pointer to an <strong>int</strong>, a pointer to a static class member of type <strong>int</strong>, and a pointer to a static member function.</p><p>        45.             Write a class template that takes two type parameters. Define a partial specialization for the first parameter, and another partial specialization that specifies the second parameter. In each specialization, introduce members that are not in the primary template.</p><p>        46.             Define a class template named <strong>Bob</strong> that takes a single type parameter. Make <strong>Bob</strong> a friend of all instances of a template class named <strong>Friendly</strong>, and a friend of a class template named <strong>Picky</strong> only when the type parameter of <strong>Bob</strong> and <strong>Picky</strong> are identical. Give <strong>Bob</strong> member functions that demonstrate its friendship.</p><empty-line/></section></section><section><title><p>6: Generic algorithms</p></title><section><p>Algorithms are at the core of computing. To be able to write an algorithm once and for all to work with any type of sequence makes your programs both simpler and safer. The ability to customize algorithms at runtime has revolutionized software development.</p><p>The subset of the standard C++ library known as the Standard Template Library (STL) was originally designed around <emphasis>generic algorithms</emphasis>—code that processes sequences of any type of values in a type-safe manner. The goal was to use predefined algorithms for almost every task, instead of hand-coding loops every time you need to process a collection of data. This power comes with a bit of a learning curve, however. By the time you get to the end of this chapter, you should be able to decide for yourself whether you find the algorithms addictive or too confusing to remember. If you’re like most people, you’ll resist them at first but then tend to use them more and more<sup>.</sup></p></section><section><title><p>A first look</p></title><section><p>Among other things, the generic algorithms in the standard library provide a <emphasis>vocabulary</emphasis> with which to describe solutions. That is, once you become familiar with the algorithms, you’ll have a new set of words with which to discuss what you’re doing, and these words are at a higher level than what you had before. You don’t have to say, "This loop moves through and assigns from here to there … oh, I see, it’s copying!" Instead, you just say <strong>copy( )</strong>. This is the kind of thing we’ve been doing in computer programming from the beginning—creating high-level abstractions to express <emphasis>what</emphasis> you’re doing and spending less time saying <emphasis>how</emphasis> you’re doing it. The <emphasis>how</emphasis> has been solved once and for all and is hidden in the algorithm’s code, ready to be reused on demand<sup>.</sup></p><p>Here’s an example of how to use the <strong>copy</strong> algorithm:</p><p>//: C06:CopyInts.cpp</p><p>// Copies ints without an explicit loop</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cstddef&gt;  // For size_t</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  int a[] = {10, 20, 30};</p><p>  const size_t SIZE = sizeof a / sizeof a[0];</p><p>  int b[SIZE];</p><p>  copy(a, a + SIZE, b);</p><p>  for (int i = 0; i &lt; SIZE; ++i)</p><p>    assert(a[i] == b[i]);</p><p>} ///:~<sup>.</sup></p><empty-line/><p>The <strong>copy</strong> algorithm’s first two parameters represent the <emphasis>range</emphasis> of the input sequence—in this case the array <strong>a</strong>. Ranges are denoted by a pair of pointers. The first points to the first element of the sequence, and the second points one position <emphasis>past the end</emphasis> of the array (right after the last element). This may seem strange at first, but it is an old C idiom that comes in quite handy. For example, the difference of these two pointers yields the number of elements in the sequence. More important, in implementing <strong>copy( )</strong>, the second pointer can act as a sentinel to stop the iteration through the sequence. The third argument refers to the beginning of the output sequence, which is the array <strong>b</strong> in this example. It is assumed that the array that <strong>b</strong> represents has enough space to receive the copied elements<sup>.</sup></p><p>The <strong>copy( )</strong> algorithm wouldn’t be very exciting if it could only process integers. It can in fact copy any sequence. The following example copies <strong>string</strong> objects<sup>.</sup></p><p>//: C06:CopyStrings.cpp</p><p>// Copies strings</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  string a[] = {"read", "my", "lips"};</p><p>  const size_t SIZE = sizeof a / sizeof a[0];</p><p>  string b[SIZE];</p><p>  copy(a, a + SIZE, b);</p><p>  assert(equal(a, a + SIZE, b));</p><p>} ///:~<sup>.</sup></p><empty-line/><p>This example introduces another algorithm, <strong>equal( )</strong>, which returns <strong>true</strong> only if each element in the first sequence is equal (using its <strong>operator==( )</strong>) to the corresponding element in the second sequence. This example traverses each sequence twice, once for the copy, and once for the comparison, without a single explicit loop!<sup>.</sup></p><p>Generic algorithms achieve this flexibility because they are function templates, of course. If you guessed that the implementation of <strong>copy( )</strong> looked something like the following, you’d be "almost" right<sup>.</sup></p><p>template&lt;typename T&gt;</p><p>void copy(T* begin, T* end, T* dest) {</p><p>  while (begin != end)</p><p>    *dest++ = *begin++;</p><p>}<sup>.</sup></p><empty-line/><p>We say "almost," because <strong>copy( )</strong> can actually process sequences delimited by anything that acts like a pointer, such as an iterator. In this way, <strong>copy( )</strong> can duplicate a vector, as in the following example<sup>.</sup></p><p>//: C06:CopyVector.cpp</p><p>// Copies the contents of a vector</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  int a[] = {10, 20, 30};</p><p>  const size_t SIZE = sizeof a / sizeof a[0];</p><p>  vector&lt;int&gt; v1(a, a + SIZE);</p><p>  vector&lt;int&gt; v2(SIZE);</p><p>  copy(v1.begin(), v1.end(), v2.begin());</p><p>  assert(equal(v1.begin(), v1.end(), v2.begin()));</p><p>} ///:~<sup>.</sup></p><empty-line/><p>The first vector, <strong>v1</strong>, is initialized from the sequence of integers in the array <strong>a</strong>. The definition of the vector <strong>v2</strong> uses a different vector constructor that makes room for <strong>SIZE</strong> elements, initialized to zero (the default value for integers).</p><p>As with the array example earlier, it’s important that <strong>v2</strong> have enough space to receive a copy of the contents of <strong>v1</strong>. For convenience, a special library function, <strong>back_inserter( )</strong>, returns a special type of iterator that <emphasis>inserts</emphasis> elements instead of <emphasis>overwriting</emphasis> them, so memory is expanded automatically by the container as needed. The following example uses <strong>back_inserter( ),</strong> so it doesn’t have to expand the size of the output vector, <strong>v2</strong>, ahead of time<sup>.</sup></p><p>//: C06:InsertVector.cpp</p><p>// Appends the contents of a vector to another</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  int a[] = {10, 20, 30};</p><p>  const size_t SIZE = sizeof a / sizeof a[0];</p><p>  vector&lt;int&gt; v1(a, a + SIZE);</p><p>  vector&lt;int&gt; v2;  // v2 is empty here</p><p>  copy(v1.begin(), v1.end(), back_inserter(v2));</p><p>  assert(equal(v1.begin(), v1.end(), v2.begin()));</p><p>} ///:~</p><empty-line/><p>The <strong>back_inserter( )</strong> function is defined in the <strong>&lt;iterator&gt;</strong> header. We’ll explain how insert iterators work in depth in the next chapter<sup>.</sup></p><p>Since iterators are identical to pointers in all essential ways, you can write the algorithms in the standard library in such a way as to allow both pointer and iterator arguments. For this reason, the implementation of <strong>copy( )</strong> looks more like the following code<sup>.</sup></p><p>template&lt;typename Iterator&gt;</p><p>void copy(Iterator begin, Iterator end, Iterator dest) {</p><p>  while (begin != end)</p><p>    *begin++ = *dest++;</p><p>}</p><empty-line/><p>Whichever argument type you use in the call, <strong>copy( )</strong> assumes it properly implements the indirection and increment operators. If it doesn’t, you’ll get a compile-time error<sup>.</sup></p></section><section><title><p>Predicates</p></title><p>At times, you might want to copy only a well-defined subset of one sequence to another, such as only those elements that satisfy a certain condition. To achieve this flexibility, many algorithms have alternate calling sequences that allow you to supply a <emphasis>predicate</emphasis>, which is simply a function that returns a Boolean value based on some criterion. Suppose, for example, that you only want to extract from a sequence of integers those numbers that are less than or equal to 15. A version of <strong>copy( )</strong> called <strong>remove_copy_if( )</strong> can do the job, like this:<sup>.</sup></p><p>//: C06:CopyInts2.cpp</p><p>// Ignores ints that satisfy a predicate</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><p>// You supply this predicate</p><p>bool gt15(int x) {</p><p>  return 15 &lt; x;</p><p>}</p><p>int main() {</p><p>  int a[] = {10, 20, 30};</p><p>  const size_t SIZE = sizeof a / sizeof a[0];</p><p>  int b[SIZE];</p><p>  int* endb = remove_copy_if(a, a+SIZE, b, gt15);</p><p>  int* beginb = b;</p><p>  while (beginb != endb)</p><p>    cout &lt;&lt; *beginb++ &lt;&lt; endl; // Prints 10 only</p><p>} ///:~<sup>.</sup></p><empty-line/><p>The <strong>remove_copy_if( )</strong> function template takes the usual range-delimiting pointers, followed by a predicate of your choosing. The predicate must be a pointer to function<sup>[79]</sup> that takes a single argument of the same type as the elements in the sequence, and it must return a <strong>bool</strong>. In this case, the function <strong>gt15</strong> returns <strong>true</strong> if its argument is greater than 15. The <strong>remove_copy_if( )</strong> algorithm applies <strong>gt15( )</strong> to each element in the input sequence and ignores those elements when writing to the output sequence<sup>.</sup></p><p>The following program illustrates yet another variation of the <strong>copy</strong> algorithm.</p><p>//: C06:CopyStrings2.cpp</p><p>// Replaces strings that satisfy a predicate</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><p>// The predicate</p><p>bool contains_e(const string&amp; s) {</p><p>  return s.find('e') != string::npos;</p><p>}</p><p>int main() {</p><p>  string a[] = {"read", "my", "lips"};</p><p>  const size_t SIZE = sizeof a / sizeof a[0];</p><p>  string b[SIZE];</p><p>  string* endb =</p><p>    replace_copy_if(a, a + SIZE, b, contains_e,</p><p>     string("kiss"));</p><p>  string* beginb = b;</p><p>  while (beginb != endb)</p><p>    cout &lt;&lt; *beginb++ &lt;&lt; endl;</p><p>} ///:~<sup>.</sup></p><empty-line/><p>Instead of just ignoring elements that don’t satisfy the predicate, <strong>replace_copy_if( )</strong> substitutes a fixed value for such elements when populating the output sequence. The output in this case is</p><p>kiss</p><p>my</p><p>lips</p><empty-line/><p>because the original occurrence of "read", the only input string containing the letter <emphasis>e</emphasis>, is replaced by the word "kiss", as specified in the last argument in the call to <strong>replace_copy_if( )</strong><sup><strong>.</strong></sup></p><p>The <strong>replace_if( )</strong> algorithm changes the original sequence in place, instead of writing to a separate output sequence, as the following program shows.</p><p>//: C06:ReplaceStrings.cpp</p><p>// Replaces strings in-place</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><p>bool contains_e(const string&amp; s) {</p><p>  return s.find('e') != string::npos;</p><p>}</p><p>int main() {</p><p>  string a[] = {"read", "my", "lips"};</p><p>  const size_t SIZE = sizeof a / sizeof a[0];</p><p>  replace_if(a, a + SIZE, contains_e, string("kiss"));</p><p>  string* p = a;</p><p>  while (p != a + SIZE)</p><p>    cout &lt;&lt; *p++ &lt;&lt; endl;</p><p>} ///:~</p><empty-line/></section><section><title><p>Stream iterators</p></title><p>Like any good software library, the Standard C++ Library attempts to provide convenient ways to automate common tasks. We mentioned in the beginning of this chapter that you can use generic algorithms in place of looping constructs. So far, however, our examples have still used an explicit loop to print their output. Since printing output is one of the most common tasks, you would hope for a way to automate that too<sup>.</sup></p><p>That’s where <emphasis>stream iterators</emphasis> come in. A stream iterator allows you to use a stream as either an input or an output sequence. To eliminate the output loop in the <strong>CopyInts2.cpp</strong> program, for instance, you can do something like the following<sup>.</sup></p><p>//: C06:CopyInts3.cpp</p><p>// Uses an output stream iterator</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>using namespace std;</p><p>bool gt15(int x) {</p><p>  return 15 &lt; x;</p><p>}</p><p>int main() {</p><p>  int a[] = {10, 20, 30};</p><p>  const size_t SIZE = sizeof a / sizeof a[0];</p><p>  remove_copy_if(a, a + SIZE,</p><p>  ostream_iterator&lt;int&gt;(cout, "\n"), gt15);</p><p>} ///:~<sup>.</sup></p><empty-line/><p>In this example we’ve replaced the output sequence <strong>b</strong> in the third argument to <strong>remove_copy_if( )</strong> with an <emphasis>output</emphasis> stream iterator, which is an instance of the <strong>ostream_iterator</strong> class template declared in the <strong>&lt;iterator&gt;</strong> header. Output stream iterators overload their copy-assignment operators to write to their stream. This particular instance of <strong>ostream_iterator</strong> is attached to the output stream <strong>cout</strong>. Every time <strong>remove_copy_if( )</strong> assigns an integer from the sequence <strong>a</strong> to <strong>cout</strong> through this iterator, the iterator writes the integer to <strong>cout</strong> and also automatically writes an instance of the separator string found in its second argument, which in this case contains just the newline character.</p><p>It is just as easy to write to a file instead of to <strong>cout</strong>, of course. All you have to do is provide an output file stream instead of <strong>cout</strong>:<sup>.</sup></p><p>//: C06:CopyIntsToFile.cpp</p><p>// Uses an output file stream iterator</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iterator&gt;</p><p>using namespace std;</p><p>bool gt15(int x) {</p><p>  return 15 &lt; x;</p><p>}</p><p>int main() {</p><p>  int a[] = {10, 20, 30};</p><p>  const size_t SIZE = sizeof a / sizeof a[0];</p><p>  ofstream outf("ints.out");</p><p>  remove_copy_if(a, a + SIZE,</p><p>  ostream_iterator&lt;int&gt;(outf, "\n"), gt15);</p><p>} ///:~<sup>.</sup></p><empty-line/><p>An <emphasis>input</emphasis> stream iterator allows an algorithm to get its input sequence from an input stream. This is accomplished by having both the constructor and <strong>operator++( )</strong> read the next element from the underlying stream and by overloading <strong>operator*( )</strong> to yield the value previously read. Since algorithms require two pointers to delimit an input sequence, you can construct an <strong>istream_iterator </strong>in two ways, as you can see in the program that follows<sup>.</sup></p><p>//: C06:CopyIntsFromFile.cpp</p><p>// Uses an input stream iterator</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><p>bool gt15(int x) {</p><p>  return 15 &lt; x;</p><p>}</p><p>int main() {</p><p>  ifstream inf("someInts.dat");</p><p>  assure(inf, "someInts.dat");</p><p>  remove_copy_if(istream_iterator&lt;int&gt;(inf),</p><p>  istream_iterator&lt;int&gt;(),</p><p>  ostream_iterator&lt;int&gt;(cout, "\n"), gt15);</p><p>} ///:~<sup>.</sup></p><empty-line/><p>The first argument to <strong>replace_copy_if( )</strong> in this program attaches an <strong>istream_iterator</strong> object to the input file stream containing <strong>int</strong>s. The second argument uses the default constructor of the <strong>istream_iterator</strong> class. This call constructs a special value of <strong>istream_iterator</strong> that indicates end-of-file, so that when the first iterator finally encounters the end of the physical file, it compares equal to the value <strong>istream_iterator&lt;int&gt;( )</strong>, allowing the algorithm to terminate correctly. Note that this example avoids using an explicit array altogether<sup>.</sup></p></section><section><title><p>Algorithm complexity</p></title><p>Using a software library is a matter of trust. You trust the implementers to not only provide correct functionality, but you also hope that the functions execute as efficiently as possible. It’s better to write your own loops than to use algorithms that degrade performance<sup>.</sup></p><p>To guarantee quality library implementations, the C++ standard not only specifies what an algorithm should do, but how fast it should do it and sometimes how much space it should use. Any algorithm that does not meet the performance requirements does not conform to the standard. The measure of an algorithm’s operational efficiency is called its <emphasis>complexity</emphasis><sup><emphasis>.</emphasis></sup></p><p>When possible, the standard specifies the exact number of operation counts an algorithm should use. The <strong>count_if( )</strong> algorithm, for example, returns the number of elements in a sequence satisfying a given predicate. The following call to <strong>count_if( )</strong>, if applied to a sequence of integers similar to the examples earlier in this chapter, yields the number of integer elements that are greater than 15:<sup>.</sup></p><p>size_t n = count_if(a, a + SIZE, gt15);</p><empty-line/><p>Since <strong>count_if( )</strong> must look at every element exactly once, it is specified to make a number of comparisons exactly equal to the number of elements in the sequence. Naturally, the <strong>copy( )</strong> algorithm has the same specification<sup>.</sup></p><p>Other algorithms can be specified to take <emphasis>at most</emphasis> a certain number of operations. The <strong>find( )</strong> algorithm searches through a sequence in order until it encounters an element equal to its third argument:<sup>.</sup></p><p>int* p = find(a, a + SIZE, 20);</p><empty-line/><p>It stops as soon as the element is found and returns a pointer to that first occurrence. If it doesn’t find one, it returns a pointer one position past the end of the sequence (<strong>a+SIZE</strong> in this example). Therefore, <strong>find</strong> is said to make at most a number of comparisons equal to the number of elements in the sequence<sup>.</sup></p><p>Sometimes the number of operations an algorithm takes cannot be measured with such precision. In such cases, the standard specifies the algorithm’s <emphasis>asymptotic complexity</emphasis>, which is a measure of how the algorithm behaves with large sequences compared to well-known formulas. A good example is the <strong>sort( )</strong> algorithm, which the standard says takes "approximately <strong>n log n</strong> comparisons on average" (<strong>n</strong> is the number of elements in the sequence).<sup>[80]</sup> Such complexity measures give a "feel" for the cost of an algorithm and at least give a meaningful basis for comparing algorithms. As you’ll see in the next chapter, the <strong>find( )</strong> member function for the <strong>set</strong> container has logarithmic complexity, which means that the cost of searching for an element in a <strong>set</strong> will, for large sets, be proportional to the logarithm of the number of elements. This is much smaller than the number of elements for large <strong>n</strong>, so it is always better to search a <strong>set</strong> by using its <strong>find( )</strong> member function rather than by using the generic <strong>find( )</strong> algorithm<sup>.</sup></p></section></section><section><title><p>Function objects</p></title><section><p>As you study some of the examples earlier in this chapter, you will probably notice the limited utility of the function <strong>gt15( )</strong>. What if you want to use a number other than 15 as a comparison threshold? You may need a <strong>gt20( )</strong> or <strong>gt25( )</strong> or others as well. Having to write a separate function for each such comparison has two distasteful difficulties:</p><p>1.       You may have to write a lot of functions!</p><p>2.      You must know all required values when you write your application code.</p><p>The second limitation means that you can’t use runtime values<sup>[81]</sup> to govern your searches, which is downright unacceptable. Overcoming this difficulty requires a way to pass information to predicates at runtime. For example, you would need a greater-than function that you can initialize with an arbitrary comparison value. Unfortunately, you can’t pass that value as a function parameter, because unary predicates, such as our <strong>gt15( )</strong>, are applied to each value in a sequence individually and must therefore take only one parameter.</p><p>The way out of this dilemma is, as always, to create an abstraction. In this case, we need an abstraction that can act like a function as well as store state, without disturbing the number of function parameters it accepts when used. This abstraction is called a <emphasis>function object</emphasis>.<sup>[82]</sup></p><p>A function object is an instance of a class that overloads <strong>operator( )</strong>, the function call operator. This operator allows an object to be used with function call syntax. As with any other object, you can initialize it via its constructors. Here is a function object that can be used in place of <strong>gt15( )</strong>:</p><p>//: C06:GreaterThanN.cpp</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><p>class gt_n {</p><p>  int value;</p><p>public:</p><p>  gt_n(int val) : value(val) {}</p><p>  bool operator()(int n) {</p><p>    return n &gt; value;</p><p>  }</p><p>};</p><p>int main() {</p><p>  gt_n f(4);</p><p>  cout &lt;&lt; f(3) &lt;&lt; endl;  // Prints 0 (for false)</p><p>  cout &lt;&lt; f(5) &lt;&lt; endl;  // Prints 1 (for true)</p><p>} ///:~</p><empty-line/><p>The fixed value to compare against (4) is passed when the function object <strong>f</strong> is created. The expression <strong>f(3)</strong> is then evaluated by the compiler as the following function call:</p><p>f.operator()(3);</p><empty-line/><p>which returns the value of the expression <strong>3 &gt; value</strong>, which is false when <strong>value</strong> is 4, as it is in this example.</p><p>Since such comparisons apply to types other than <strong>int</strong>, it would make sense to define <strong>gt_n( )</strong> as a class template. It turns out you don’t have to do it yourself, though—the standard library has already done it for you. The following descriptions of function objects should not only make that topic clear, but also give you a better understanding of how the generic algorithms work<sup>.</sup></p></section><section><title><p>Classification of function objects</p></title><p>The standard C++ library classifies function objects based on the number of arguments that their <strong>operator( )</strong> takes and the kind of value it returns. This classification is organized according to whether a function object’s <strong>operator( )</strong> takes zero, one, or two arguments, as the following definitions illustrate<sup>.</sup></p><p><strong>Generator</strong>: A type of function object that takes <emphasis>no arguments</emphasis> and returns a value of an arbitrary type. A random number generator is an example of a generator. The standard library provides one generator, the function <strong>rand( )</strong> declared in <strong>&lt;cstdlib&gt;</strong>, and has some algorithms, such as <strong>generate_n( )</strong>, which apply generators to a sequence<sup>.</sup></p><p><strong>Unary Function</strong>: A type of function object that takes a <emphasis>single argument</emphasis> of any type and returns a value that may be of a different type (which may be <strong>void</strong>)<sup>.</sup></p><p><strong>Binary Function</strong>: A type of function object that takes <emphasis>two arguments</emphasis> of any two (possibly distinct) types and returns a value of any type (including <strong>void</strong>)<sup>.</sup></p><p><strong>Unary Predicate</strong>: A Unary Function that returns a <strong>bool</strong>.</p><p><strong>Binary Predicate</strong>: A Binary Function that returns a <strong>bool</strong>.</p><p><strong>Strict Weak Ordering</strong>: A binary predicate that allows for a more general interpretation of "equality." Some of the standard containers consider two elements equivalent if neither is less than the other (using <strong>operator&lt;( )</strong>). This is important when comparing floating-point values, and objects of other types where <strong>operator==( )</strong> is unreliable or unavailable. This notion also applies if you want to sort a sequence of data records (<strong>struct</strong>s) on a subset of the <strong>struct</strong>’s fields, that comparison scheme is considered a strict weak ordering because two records with equal keys are not really "equal" as total objects, but they are equal as far as the comparison you’re using is concerned. The importance of this concept will become clearer in the next chapter<sup>.</sup></p><p>In addition, certain algorithms make assumptions about the operations available for the types of objects they process. We will use the following terms to indicate these assumptions:<sup>.</sup></p><p><strong>LessThanComparable</strong>: A class that has a less-than <strong>operator&lt;</strong><sup><strong>.</strong></sup></p><p><strong>Assignable</strong>: A class that has a copy-assignment <strong>operator=</strong> for its own type<sup>.</sup></p><p><strong>EqualityComparable</strong>: A class that has an equivalence <strong>operator==</strong> for its own type<sup>.</sup></p><p>We will use these terms later in this chapter to describe the generic algorithms in the standard library.</p></section><section><title><p>Automatic creation of function objects</p></title><p>The <strong>&lt;functional&gt;</strong> header defines a number of useful generic function objects. They are admittedly simple, but you can use them to compose more complicated function objects. Consequently, in many instances, you can construct complicated predicates without writing a single function yourself! You do so by using <emphasis>function object adapters</emphasis> to take the simple function objects and adapt them for use with other function objects in a chain of operations<sup>.</sup></p><p>To illustrate, let’s use only standard function objects to accomplish what <strong>gt15( )</strong> did earlier. The standard function object, <strong>greater</strong>, is a <emphasis>binary</emphasis> function object that returns <strong>true</strong> if its first argument is greater than its second argument. We cannot apply this directly to a sequence of integers through an algorithm such as <strong>remove_copy_if( )</strong>, because <strong>remove_copy_if( )</strong> expects a <emphasis>unary</emphasis> predicate. No problem. We can construct a unary predicate on the fly that uses <strong>greater</strong> to compare its first argument to a <emphasis>fixed value</emphasis>. We fix the value of the second parameter that <strong>greater</strong> will use to be 15 with the function object adapter <strong>bind2nd</strong>, like this:<sup>.</sup></p><p>//: C06:CopyInts4.cpp</p><p>// Uses a standard function object and adapter</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>using namespace std;</p><p>int main() {</p><p>  int a[] = {10, 20, 30};</p><p>  const size_t SIZE = sizeof a / sizeof a[0];</p><p>  remove_copy_if(a, a + SIZE,</p><p>  ostream_iterator&lt;int&gt;(cout, "\n"),</p><p>  bind2nd(greater&lt;int&gt;(), 15));</p><p>} ///:~<sup>.</sup></p><empty-line/><p>This program accomplishes the same thing as <strong>CopyInts3.cpp</strong>, but without our having to write our own predicate function <strong>gt15( )</strong>. The function object adapter <strong>bind2nd( )</strong> is a template function that creates a function object of type <strong>binder2nd</strong>, which simply stores the two arguments passed to <strong>bind2nd( )</strong>, the first of which must be a binary function or function object (that is, anything that can be called with two arguments). The <strong>operator( )</strong> function in <strong>binder2nd</strong>, which is itself a unary function, calls the binary function it stored, passing it its incoming parameter and the fixed value it stored<sup>.</sup></p><p>To make the explanation concrete for this example, let’s call the instance of <strong>binder2nd</strong> created by <strong>bind2nd( )</strong> by the name <strong>b</strong>. When <strong>b</strong> is created, it receives two parameters (<strong>greater&lt;int&gt;( )</strong> and 15) and stores them. Let’s call the instance of <strong>greater&lt;int&gt;</strong> by the name <strong>g</strong>. For convenience, let’s also call the instance of the output stream iterator by the name <strong>o</strong>. Then the call to <strong>remove_copy_if( )</strong> earlier becomes the following:<sup>.</sup></p><p>remove_copy_if(a, a + SIZE, o, b(g, 15).operator());</p><empty-line/><p>As <strong>remove_copy_if( )</strong> iterates through the sequence, it calls <strong>b</strong> on each element, to determine whether to ignore the element when copying to the destination. If we denote the current element by the name <strong>e</strong>, that call inside <strong>remove_copy_if( )</strong> is equivalent to<sup>.</sup></p><p>if (b(e))</p><empty-line/><p>but <strong>binder2nd</strong>’s function call operator just turns around and calls <strong>g(e,15)</strong>, so the earlier call is the same as<sup>.</sup></p><p>if (greater&lt;int&gt;(e, 15))</p><empty-line/><p>which is the comparison we were seeking. There is also a <strong>bind1st( )</strong> adapter that creates a <strong>binder1st</strong> object, which fixes the <emphasis>first</emphasis> argument of the associated input binary function<sup>.</sup></p><p>As another example, let’s count the number of elements in the sequence not equal to 20. This time we’ll use the algorithm <strong>count_if( )</strong>, introduced earlier. There is a standard binary function object, <strong>equal_to</strong>, and also a function object adapter, <strong>not1( )</strong>, that take a unary function object as a parameter and invert its truth value. The following program will do the job<sup>.</sup></p><p>//: C06:CountNotEqual.cpp</p><p>// Count elements not equal to 20</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><p>int main() {</p><p>  int a[] = {10, 20, 30};</p><p>  const size_t SIZE = sizeof a / sizeof a[0];</p><p>  cout &lt;&lt; count_if(a, a + SIZE,</p><p>    not1(bind1st(equal_to&lt;int&gt;(), 20)));// 2</p><p>} ///:~<sup>.</sup></p><empty-line/><p>As <strong>remove_copy_if( )</strong> did in the previous example, <strong>count_if( )</strong> calls the predicate in its third argument (let’s call it <strong>n</strong>) for each element of its sequence and increments its internal counter each time <strong>true</strong> is returned. If, as before, we call the current element of the sequence by the name <strong>e</strong>, the statement<sup>.</sup></p><p>if (n(e))</p><empty-line/><p>in the implementation of <strong>count_if </strong>is interpreted as</p><p>if (!bind1st(equal_to&lt;int&gt;, 20)(e))</p><empty-line/><p>which of course ends up as</p><p>if (!equal_to&lt;int&gt;(20, e))</p><empty-line/><p>because <strong>not1( )</strong> returns the logical negation of the result of calling its unary function argument. The first argument to <strong>equal_to</strong> is 20 in this case because we used <strong>bind1st( )</strong> instead of <strong>bind2nd( )</strong>. Since testing for equality is symmetric in its arguments, we could have used either <strong>bind1st( )</strong> or <strong>bind2nd( )</strong> in this example<sup>.</sup></p><p>The following table shows the templates that generate the standard function objects, along with the kinds of expressions to which they apply<sup>.</sup></p><table><tr align="left"><th align="left" valign="top">Name</th><th align="left" valign="top">Type</th><th align="left" valign="top">Result produced </th></tr><tr align="left"><td align="left" valign="top">plus</td><td align="left" valign="top">BinaryFunction</td><td align="left" valign="top">arg1 + arg2</td></tr><tr align="left"><td align="left" valign="top">minus</td><td align="left" valign="top">BinaryFunction</td><td align="left" valign="top">arg1 - arg2</td></tr><tr align="left"><td align="left" valign="top">multiplies</td><td align="left" valign="top">BinaryFunction</td><td align="left" valign="top">arg1 * arg2</td></tr><tr align="left"><td align="left" valign="top">divides</td><td align="left" valign="top">BinaryFunction</td><td align="left" valign="top">arg1 / arg2</td></tr><tr align="left"><td align="left" valign="top">modulus</td><td align="left" valign="top">BinaryFunction</td><td align="left" valign="top">arg1 % arg2</td></tr><tr align="left"><td align="left" valign="top">negate</td><td align="left" valign="top">UnaryFunction</td><td align="left" valign="top">- arg1</td></tr><tr align="left"><td align="left" valign="top">equal_to</td><td align="left" valign="top">BinaryPredicate</td><td align="left" valign="top">arg1 == arg2</td></tr><tr align="left"><td align="left" valign="top">not_equal_to</td><td align="left" valign="top">BinaryPredicate</td><td align="left" valign="top">arg1 != arg2</td></tr><tr align="left"><td align="left" valign="top">greater</td><td align="left" valign="top">BinaryPredicate</td><td align="left" valign="top">arg1 &gt; arg2</td></tr><tr align="left"><td align="left" valign="top">less</td><td align="left" valign="top">BinaryPredicate</td><td align="left" valign="top">arg1 &lt; arg2</td></tr><tr align="left"><td align="left" valign="top">greater_equal</td><td align="left" valign="top">BinaryPredicate</td><td align="left" valign="top">arg1 &gt;= arg2</td></tr><tr align="left"><td align="left" valign="top">less_equal</td><td align="left" valign="top">BinaryPredicate</td><td align="left" valign="top">arg1 &lt;= arg2</td></tr><tr align="left"><td align="left" valign="top">logical_and</td><td align="left" valign="top">BinaryPredicate</td><td align="left" valign="top">arg1 &amp;&amp; arg2</td></tr><tr align="left"><td align="left" valign="top">logical_or</td><td align="left" valign="top">BinaryPredicate</td><td align="left" valign="top">arg1 || arg2</td></tr><tr align="left"><td align="left" valign="top">logical_not</td><td align="left" valign="top">UnaryPredicate</td><td align="left" valign="top">!arg1</td></tr><tr align="left"><td align="left" valign="top">unary_negate</td><td align="left" valign="top">Unary Logical</td><td align="left" valign="top">!(UnaryPredicate(arg1))</td></tr><tr align="left"><td align="left" valign="top">binary_negate</td><td align="left" valign="top">Binary Logical</td><td align="left" valign="top">!(BinaryPredicate(arg1, arg2))</td></tr></table></section><section><title><p>Adaptable function objects</p></title><p>Standard function adapters such as <strong>bind1st( )</strong> and <strong>bind2nd( )</strong> make some assumptions about the function objects they process. To illustrate, consider the following expression from the last line of the earlier <strong>CountNotEqual.cpp</strong> program:<sup>.</sup></p><p>not1(bind1st(equal_to&lt;int&gt;(), 20))</p><empty-line/><p>The <strong>bind1st( )</strong> adapter creates a unary function object of type <strong>binder1st</strong>, which simply stores an instance of <strong>equal_to&lt;int&gt;</strong> and the value 20. The <strong>binder1st::operator( )</strong> function needs to know its argument type and its return type; otherwise, it will not have a valid declaration. The convention to solve this problem is to expect all function objects to provide nested type definitions for these types. For unary functions, the type names are <strong>argument_type</strong> and <strong>result_type</strong>; for binary function objects they are <strong>first_argument_type</strong>, <strong>second_argument_type</strong>, and <strong>result_type</strong>. Looking at the implementation of <strong>bind1st( )</strong> and <strong>binder1st</strong> in the <strong>&lt;functional&gt;</strong> header reveals these expectations. First inspect <strong>bind1st( )</strong>, as it might appear in a typical library implementation:<sup>.</sup></p><p>template &lt;class Op, class T&gt;</p><p>binder1st&lt;Op&gt;</p><p>bind1st(const Op&amp; f, const T&amp; val)</p><p>{</p><p>  typedef typename Op::first_argument_type Arg1_t;</p><p>  return binder1st&lt;Op&gt;(f, Arg1_t(val));</p><p>}</p><empty-line/><p>Note that the template parameter, <strong>Op</strong>, which represents the type of the binary function being adapted by <strong>bind1st( )</strong>, must have a nested type named <strong>first_argument_type</strong>. (Note also the use of <strong>typename</strong> to inform the compiler that it is a member <emphasis>type</emphasis> name, as explained in Chapter 5.) Now notice how <strong>binder1st</strong> uses the type names in <strong>Op</strong> in its declaration of its function call operator:<sup>.</sup></p><p>// Inside the implementation for binder1st&lt;Op&gt;…</p><p>typename Op::result_type</p><p>operator()(const typename Op::second_argument_type&amp; x)</p><p>  const;</p><empty-line/><p>Function objects whose classes provide these type names are called <emphasis>adaptable function objects</emphasis><sup><emphasis>.</emphasis></sup></p><p>Since these names are expected of all standard function objects as well as of any function objects you create that you want to use with the function object adapters, the <strong>&lt;functional&gt;</strong> header provides two templates that define these types for you: <strong>unary_function</strong> and <strong>binary_function</strong>. You simply derive from these classes while filling in the argument types as template parameters. Suppose, for example, that we want to make the function object <strong>gt_n</strong>, defined earlier in this chapter, adaptable. All we need to do is the following:<sup>.</sup></p><p>class gt_n : public unary_function&lt;int, bool&gt; {</p><p>  int value;</p><p>public:</p><p>  gt_n(int val) : value(val) {}</p><p>  bool operator()(int n) {</p><p>    return n &gt; value;</p><p>  }</p><p>};<sup>.</sup></p><empty-line/><p>All <strong>unary_function</strong> does is to provide the appropriate type definitions, which it infers from its template parameters as you can see in its definition:<sup>.</sup></p><p>template &lt;class Arg, class Result&gt;</p><p>struct unary_function {</p><p>  typedef Arg argument_type;</p><p>  typedef Result result_type;</p><p>};</p><empty-line/><p>These types become accessible through <strong>gt_n</strong> because it derives publicly from <strong>unary_function</strong>. The <strong>binary_function</strong> template behaves in a similar manner<sup>.</sup></p></section><section><title><p>More function object examples</p></title><p>The following <strong>FunctionObjects.cpp</strong> example provides simple tests for most of the built-in basic function object templates. This way, you can see how to use each template, along with their resulting behavior. This example uses one of the following generators for convenience:<sup>.</sup></p><p>//: C06:Generators.h</p><p>// Different ways to fill sequences</p><p>#ifndef GENERATORS_H</p><p>#define GENERATORS_H</p><p>#include &lt;set&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;cstring&gt;</p><p>#include &lt;ctime&gt;</p><p>// Microsoft namespace work-around</p><p>#ifndef _MSC_VER</p><p>using std::rand;</p><p>using std::srand;</p><p>using std::time;</p><p>#endif</p><p>// A generator that can skip over numbers:</p><p>class SkipGen {</p><p>  int i;</p><p>  int skp;</p><p>public:</p><p>  SkipGen(int start = 0, int skip = 1)</p><p>    : i(start), skp(skip) {}</p><p>  int operator()() {</p><p>    int r = i;</p><p>    i += skp;</p><p>    return r;</p><p>  }</p><p>};</p><empty-line/><p>// Generate unique random numbers from 0 to mod:</p><p>class URandGen {</p><p>  std::set&lt;int&gt; used;</p><p>  int limit;</p><p>public:</p><p>  URandGen(int lim) : limit(lim) {</p><p>    srand(time(0));</p><p>  }</p><p>  int operator()() {</p><p>    while(true) {</p><p>      int i = int(rand()) % limit;</p><p>      if(used.find(i) == used.end()) {</p><p>        used.insert(i);</p><p>        return i;</p><p>      }</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>// Produces random characters:</p><p>class CharGen {</p><p>  static const char* source;</p><p>  static const int len;</p><p>public:</p><p>  CharGen() { srand(time(0)); }</p><p>  char operator()() {</p><p>    return source[rand() % len];</p><p>  }</p><p>};</p><empty-line/><p>// Statics created here for convenience, but</p><p>// will cause problems if multiply included:</p><p>const char* CharGen::source = "ABCDEFGHIJK"</p><p>  "LMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";</p><p>const int CharGen::len = strlen(source);</p><p>#endif // GENERATORS_H ///:~</p><empty-line/><p>We’ll be using these generating functions in various examples throughout this chapter. The <strong>SkipGen</strong> function object returns the next number of an arithmetic sequence whose common difference is held in its <strong>skp</strong> data member. A <strong>URandGen</strong> object generates a unique random number in a specified range. (It uses a <strong>set</strong> container, which we’ll discuss in the next chapter.) A <strong>CharGen</strong> object returns a random alphabetic character. Here is the sample program we promised, which uses <strong>URandGen</strong><sup><strong>.</strong></sup></p><p>//: C06:FunctionObjects.cpp</p><p>//{-bor}</p><p>// Illustrates selected predefined function object</p><p>// templates from the standard C++ library</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;vector&gt;</p><p>#include "Generators.h"</p><p>using namespace std;</p><empty-line/><p>template&lt;class Iter&gt;</p><p>void print(Iter b, Iter e, char* msg = "") {</p><p>  if(msg != 0 &amp;&amp; *msg != 0)</p><p>    cout &lt;&lt; msg &lt;&lt; ":" &lt;&lt; endl;</p><p>  typedef typename Iter::value_type T;</p><p>  copy(b, e, ostream_iterator&lt;T&gt;(cout, " "));</p><p>  cout &lt;&lt; endl;</p><p>}</p><empty-line/><p>template&lt;typename Contain, typename UnaryFunc&gt;</p><p>void testUnary(Contain&amp; source, Contain&amp; dest,</p><p>  UnaryFunc f) {</p><p>  transform(source.begin(), source.end(),</p><p>    dest.begin(), f);</p><p>}</p><empty-line/><p>template&lt;typename Contain1, typename Contain2,</p><p>  typename BinaryFunc&gt;</p><p>void testBinary(Contain1&amp; src1, Contain1&amp; src2,</p><p>  Contain2&amp; dest, BinaryFunc f) {</p><p>  transform(src1.begin(), src1.end(),</p><p>    src2.begin(), dest.begin(), f);</p><p>}</p><empty-line/><p>// Executes the expression, then stringizes the</p><p>// expression into the print statement:</p><p>#define T(EXPR) EXPR; print(r.begin(), r.end(), \</p><p>  "After " #EXPR);</p><p>// For Boolean tests:</p><p>#define B(EXPR) EXPR; print(br.begin(), br.end(), \</p><p>  "After " #EXPR);</p><empty-line/><p>// Boolean random generator:</p><p>struct BRand {</p><p>  BRand() { srand(time(0)); }</p><p>  bool operator()() {</p><p>    return rand() &gt; RAND_MAX / 2;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  const int sz = 10;</p><p>  const int max = 50;</p><p>  vector&lt;int&gt; x(sz), y(sz), r(sz);</p><p>  // An integer random number generator:</p><p>  URandGen urg(max);</p><p>  generate_n(x.begin(), sz, urg);</p><p>  generate_n(y.begin(), sz, urg);</p><p>  // Add one to each to guarantee nonzero divide:</p><p>  transform(y.begin(), y.end(), y.begin(),</p><p>    bind2nd(plus&lt;int&gt;(), 1));</p><p>  // Guarantee one pair of elements is ==:</p><p>  x[0] = y[0];</p><p>  print(x.begin(), x.end(), "x");</p><p>  print(y.begin(), y.end(), "y");</p><p>  // Operate on each element pair of x &amp; y,</p><p>  // putting the result into r:</p><p>  T(testBinary(x, y, r, plus&lt;int&gt;()));</p><p>  T(testBinary(x, y, r, minus&lt;int&gt;()));</p><p>  T(testBinary(x, y, r, multiplies&lt;int&gt;()));</p><p>  T(testBinary(x, y, r, divides&lt;int&gt;()));</p><p>  T(testBinary(x, y, r, modulus&lt;int&gt;()));</p><p>  T(testUnary(x, r, negate&lt;int&gt;()));</p><p>  vector&lt;bool&gt; br(sz); // For Boolean results</p><p>  B(testBinary(x, y, br, equal_to&lt;int&gt;()));</p><p>  B(testBinary(x, y, br, not_equal_to&lt;int&gt;()));</p><p>  B(testBinary(x, y, br, greater&lt;int&gt;()));</p><p>  B(testBinary(x, y, br, less&lt;int&gt;()));</p><p>  B(testBinary(x, y, br, greater_equal&lt;int&gt;()));</p><p>  B(testBinary(x, y, br, less_equal&lt;int&gt;()));</p><p>  B(testBinary(x, y, br,</p><p>    not2(greater_equal&lt;int&gt;())));</p><p>  B(testBinary(x,y,br,not2(less_equal&lt;int&gt;())));</p><p>  vector&lt;bool&gt; b1(sz), b2(sz);</p><p>  generate_n(b1.begin(), sz, BRand());</p><p>  generate_n(b2.begin(), sz, BRand());</p><p>  print(b1.begin(), b1.end(), "b1");</p><p>  print(b2.begin(), b2.end(), "b2");</p><p>  B(testBinary(b1, b2, br, logical_and&lt;int&gt;()));</p><p>  B(testBinary(b1, b2, br, logical_or&lt;int&gt;()));</p><p>  B(testUnary(b1, br, logical_not&lt;int&gt;()));</p><p>  B(testUnary(b1, br, not1(logical_not&lt;int&gt;())));</p><p>} ///:~</p><empty-line/><p>To keep this example short, we used a few handy tricks. The <strong>print( )</strong> template is designed to print any sequence, along with an optional message. Since <strong>print( )</strong> uses the <strong>copy( )</strong> algorithm to send objects to <strong>cout</strong> via an <strong>ostream_iterator</strong>, the <strong>ostream_iterator</strong> must know the type of object it is printing, which we infer from the <strong>value_type</strong> member of the iterator passed.<sup>[83]</sup> As you can see in <strong>main( )</strong>, however, the compiler can deduce the type of <strong>T</strong> when you hand it a <strong>vector&lt;T&gt;</strong>, so you don’t have to specify that template argument explicitly; you just say <strong>print(x)</strong> to print the <strong>vector&lt;T&gt; x</strong><sup><strong>.</strong></sup></p><p>The next two template functions automate the process of testing the various function object templates. There are two since the function objects are either unary or binary. The <strong>testUnary( )</strong> function takes a source vector, a destination vector, and a unary function object to apply to the source vector to produce the destination vector. In <strong>testBinary( )</strong>, two source vectors are fed to a binary function to produce the destination vector. In both cases, the template functions simply turn around and call the <strong>transform( )</strong> algorithm, which applies the unary function/function object found in its fourth parameter to each sequence element, writing the result to the sequence indicated by its third parameter, which in this case is the same as the input sequence<sup>.</sup></p><p>For each test, you want to see a string describing the test, followed by the results of the test. To automate this, the preprocessor comes in handy; the <strong>T( )</strong> and <strong>B( )</strong> macros each take the expression you want to execute. After evaluating the expression, they pass the appropriate range to <strong>print( )</strong>. To produce the message the expression is "string-ized" using the preprocessor. That way you see the code of the expression that is executed followed by the result vector<sup>.</sup></p><p>The last little tool, <strong>BRand</strong>, is a generator object that creates random <strong>bool</strong> values. To do this, it gets a random number from <strong>rand( )</strong> and tests to see if it’s greater than <strong>(RAND_MAX+1)/2</strong>. If the random numbers are evenly distributed, this should happen half the time<sup>.</sup></p><p>In <strong>main( )</strong>, three vectors of <strong>int</strong> are created: <strong>x</strong> and <strong>y</strong> for source values, and <strong>r</strong> for results. To initialize <strong>x</strong> and <strong>y</strong> with random values no greater than 50, a generator of type <strong>URandGen</strong> from <strong>Generators.h</strong> is used. The standard <strong>generate_n( )</strong> algorithm populates the sequence specified in its first argument by invoking its third argument (which must be a generator) a given number of times (specified in its second argument). Since there is one operation in which elements of <strong>x</strong> are divided by elements of <strong>y</strong>, we must ensure that there are no zero values of <strong>y</strong>. This is accomplished by once again using the <strong>transform( )</strong> algorithm, taking the source values from <strong>y</strong> and putting the results back into <strong>y</strong>. The function object for this is created with the expression:<sup>.</sup></p><p>bind2nd(plus&lt;int&gt;(), 1)</p><empty-line/><p>This expression uses the <strong>plus</strong> function object to add 1 to its first argument. As we did earlier in this chapter, we use a binder adapter to make this a unary function so it can applied to the sequence by a single call to <strong>transform( )</strong><sup><strong>.</strong></sup></p><p>Another test in the program compares the elements in the two vectors for equality, so it is interesting to guarantee that at least one pair of elements is equivalent; in this case element zero is chosen<sup>.</sup></p><p>Once the two vectors is printed, <strong>T( )</strong> tests each of the function objects that produces a numeric value, and then <strong>B( )</strong> tests each function object that produces a Boolean result. The result is placed into a <strong>vector&lt;bool&gt;</strong>, and when this vector is printed, it produces a ‘<strong>1</strong>’ for a true value and a ‘<strong>0</strong>’ for a false value. Here is the output from an execution of <strong>FunctionObjects.cpp</strong>:<sup>.</sup></p><p>x:</p><p>4 8 18 36 22 6 29 19 25 47</p><p>y:</p><p>4 14 23 9 11 32 13 15 44 30</p><p>After testBinary(x, y, r, plus&lt;int&gt;()):</p><p>8 22 41 45 33 38 42 34 69 77</p><p>After testBinary(x, y, r, minus&lt;int&gt;()):</p><p>0 -6 -5 27 11 -26 16 4 -19 17</p><p>After testBinary(x, y, r, multiplies&lt;int&gt;()):</p><p>16 112 414 324 242 192 377 285 1100 1410</p><p>After testBinary(x, y, r, divides&lt;int&gt;()):</p><p>1 0 0 4 2 0 2 1 0 1</p><p>After testBinary(x, y, r, limit&lt;int&gt;()):</p><p>0 8 18 0 0 6 3 4 25 17</p><p>After testUnary(x, r, negate&lt;int&gt;()):</p><p>-4 -8 -18 -36 -22 -6 -29 -19 -25 -47</p><p>After testBinary(x, y, br, equal_to&lt;int&gt;()):</p><p>1 0 0 0 0 0 0 0 0 0</p><p>After testBinary(x, y, br, not_equal_to&lt;int&gt;()):</p><p>0 1 1 1 1 1 1 1 1 1</p><p>After testBinary(x, y, br, greater&lt;int&gt;()):</p><p>0 0 0 1 1 0 1 1 0 1</p><p>After testBinary(x, y, br, less&lt;int&gt;()):</p><p>0 1 1 0 0 1 0 0 1 0</p><p>After testBinary(x, y, br, greater_equal&lt;int&gt;()):</p><p>1 0 0 1 1 0 1 1 0 1</p><p>After testBinary(x, y, br, less_equal&lt;int&gt;()):</p><p>1 1 1 0 0 1 0 0 1 0</p><p>After testBinary(x, y, br, not2(greater_equal&lt;int&gt;())):</p><p>0 1 1 0 0 1 0 0 1 0</p><p>After testBinary(x,y,br,not2(less_equal&lt;int&gt;())):</p><p>0 0 0 1 1 0 1 1 0 1</p><p>b1:</p><p>0 1 1 0 0 0 1 0 1 1</p><p>b2:</p><p>0 1 1 0 0 0 1 0 1 1</p><p>After testBinary(b1, b2, br, logical_and&lt;int&gt;()):</p><p>0 1 1 0 0 0 1 0 1 1</p><p>After testBinary(b1, b2, br, logical_or&lt;int&gt;()):</p><p>0 1 1 0 0 0 1 0 1 1</p><p>After testUnary(b1, br, logical_not&lt;int&gt;()):</p><p>1 0 0 1 1 1 0 1 0 0</p><p>After testUnary(b1, br, not1(logical_not&lt;int&gt;())):</p><p>0 1 1 0 0 0 1 0 1 1</p><empty-line/><p>A binder doesn’t have to produce a unary <emphasis>predicate</emphasis>; it can also create any unary <emphasis>function</emphasis> (that is, a function that returns something other than <strong>bool</strong>). For example, suppose you’d like to multiply every element in a <strong>vector</strong> by 10. Using a binder with the <strong>transform( )</strong> algorithm does the trick:<sup>.</sup></p><p>//: C06:FBinder.cpp</p><p>// Binders aren't limited to producing predicates</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;vector&gt;</p><p>#include "Generators.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  ostream_iterator&lt;int&gt; out(cout," ");</p><p>  vector&lt;int&gt; v(15);</p><p>  generate(v.begin(), v.end(), URandGen(20));</p><p>  copy(v.begin(), v.end(), out);</p><p>  transform(v.begin(), v.end(), v.begin(),</p><p>            bind2nd(multiplies&lt;int&gt;(), 10));</p><p>  copy(v.begin(), v.end(), out);</p><p>} ///:~</p><empty-line/><p>Since the third argument to <strong>transform( ) </strong>is the same as the first, the resulting elements are copied back into the source vector. The function object created by <strong>bind2nd( )</strong> in this case produces an <strong>int</strong> result<sup>.</sup></p><p>The "bound" argument to a binder cannot be a function object, but it does not have to be a compile-time constant. For example:<sup>.</sup></p><p>//: C06:BinderValue.cpp</p><p>// The bound argument can vary</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>using namespace std;</p><empty-line/><p>int boundedRand() { return rand() % 100; }</p><empty-line/><p>int main() {</p><p>  const int sz = 20;</p><p>  int a[sz], b[sz] = {0};</p><p>  generate(a, a + sz, boundedRand);</p><p>  int val = boundedRand();</p><p>  int* end = remove_copy_if(a, a + sz, b,</p><p>             bind2nd(greater&lt;int&gt;(), val));</p><p>  // Sort for easier viewing:</p><p>  sort(a, a + sz);</p><p>  sort(b, end);</p><p>  ostream_iterator&lt;int&gt; out(cout, " ");</p><p>  cout &lt;&lt; "Original Sequence:\n";</p><p>  copy(a, a + sz, out); cout &lt;&lt; endl;</p><p>  cout &lt;&lt; "Values less &lt;= " &lt;&lt; val &lt;&lt; endl;</p><p>  copy(b, end, out); cout &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><empty-line/><p>Here, an array is filled with 20 random numbers between 0 and 100, and the user provides a value on the command line. In the <strong>remove_copy_if( )</strong> call, you can see that the bound argument to <strong>bind2nd( )</strong> is random number in the same range as the sequence. The output of a sample execution follows<sup>.</sup></p><p>Original Sequence:</p><p>4 12 15 17 19 21 26 30 47 48 56 58 60 63 71 79 82 90 92 95</p><p>Values less &lt;= 41</p><p>4 12 15 17 19 21 26 30</p><empty-line/></section><section><title><p>Function pointer adapters</p></title><p>Wherever a function-like entity is expected by an algorithm, you can supply either a pointer to an ordinary function or a function object. When the algorithm issues a call, if it is through a function pointer, than the native function-call mechanism is used. If it through a function object, then that objects <strong>operator( )</strong> member executes. You saw earlier, for example, that we passed a raw function, <strong>gt15( )</strong>, as a predicate to <strong>remove_copy_if( )</strong> in the program <strong>CopyInts2.cpp</strong>. We also passed pointers to functions returning random numbers to <strong>generate( )</strong> and <strong>generate_n( )</strong><sup><strong>.</strong></sup></p><p>You cannot, however, use raw functions with function object adapters, such as <strong>bind2nd( )</strong>, because they assume the existence of type definitions for the argument and result types. Instead of manually converting your native functions into function objects yourself, the standard library provides a family of adapters to do the work for you. The <strong>ptr_fun( ) </strong>adapters take a pointer to a function and turn it into a function object. They are not designed for a function that takes no arguments—they must only be used with unary functions or binary functions<sup>.</sup></p><p>The following program uses <strong>ptr_fun( )</strong> to wrap a unary function.</p><p>//: C06:PtrFun1.cpp</p><p>// Using ptr_fun() with a unary function</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cmath&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>int d[] = {123, 94, 10, 314, 315};</p><p>const int dsz = sizeof d / sizeof *d;</p><p>bool isEven(int x) {</p><p>  return x % 2 == 0;</p><p>}</p><p>int main() {</p><p>  vector&lt;bool&gt; vb;</p><p>  transform(d, d + dsz, back_inserter(vb),</p><p>    not1(ptr_fun(isEven)));</p><p>  copy(vb.begin(), vb.end(),</p><p>    ostream_iterator&lt;bool&gt;(cout, " "));</p><p>  cout &lt;&lt; endl;</p><p>  // Output: 1 0 0 0 1</p><p>} ///:~</p><empty-line/><p>We can’t simply pass <strong>isEven</strong> to <strong>not1</strong>, because <strong>not1</strong> needs to know the actual argument type and return type its argument uses. The <strong>ptr_fun( )</strong> adapter deduces those types through template argument deduction. The definition of the unary version of <strong>ptr_fun( )</strong> looks something like this:<sup>.</sup></p><p>template &lt;class Arg, class Result&gt;</p><p>pointer_to_unary_function&lt;Arg, Result&gt;</p><p>ptr_fun(Result (*fptr)(Arg))</p><p>{</p><p>  return pointer_to_unary_function&lt;Arg, Result&gt;(fptr);</p><p>}</p><empty-line/><p>As you can see, this version of <strong>ptr_fun( )</strong> deduces the argument and result types from <strong>fptr</strong> and uses them to initialize a <strong>pointer_to_unary_function</strong> object that stores <strong>fptr</strong>. The function call operator for <strong>pointer_to_unary_function</strong> just calls <strong>fptr</strong>, as you can see by the last line of its code:<sup>.</sup></p><p>template &lt;class Arg, class Result&gt;</p><p>class pointer_to_unary_function</p><p>: public unary_function&lt;Arg, Result&gt; {</p><p>  Result (*fptr)(Arg); // stores the f-ptr</p><p>public:</p><p>  pointer_to_unary_function(Result (*x)(Arg))</p><p>    : fptr(x) {}</p><p>  Result operator()(Arg x) const {return fptr(x);}</p><p>};</p><empty-line/><p>Since <strong>pointer_to_unary_function</strong> derives from <strong>unary_function</strong>, the appropriate type definitions come along for the ride and are available to <strong>not1</strong><sup><strong>.</strong></sup></p><p>There is also a binary version of <strong>ptr_fun( ),</strong> which returns a <strong>pointer_to_binary_function</strong> object (which derives from <strong>binary_function</strong>, of course) that behaves analogously to the unary case. The following program uses the binary version of <strong>ptr_fun( )</strong> to raise numbers in a sequence to a power. It also reveals a "gotcha" when passing overloaded functions to <strong>ptr_fun( )</strong><sup><strong>.</strong></sup></p><p>//: C06:PtrFun2.cpp</p><p>// Using ptr_fun() for a binary function</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cmath&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>double d[] = { 01.23, 91.370, 56.661,</p><p>  023.230, 19.959, 1.0, 3.14159 };</p><p>const int dsz = sizeof d / sizeof *d;</p><empty-line/><p>int main() {</p><p>  vector&lt;double&gt; vd;</p><p>  transform(d, d + dsz, back_inserter(vd),</p><p>    bind2nd(ptr_fun&lt;double, double, double&gt;(pow), 2.0));</p><p>  copy(vd.begin(), vd.end(),</p><p>    ostream_iterator&lt;double&gt;(cout, " "));</p><p>  cout &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The <strong>pow( )</strong> function is overloaded in the standard C++ header <strong>&lt;cmath&gt;</strong> for each of the floating-point data types, as follows:</p><p>float pow(float, int);  // efficient int power versions…</p><p>double pow(double, int);</p><p>long double pow(long double, int);</p><p>float pow(float, float);</p><p>double pow(double, double);</p><p>long double pow(long double, long double);</p><empty-line/><p>Since there are multiple versions of <strong>pow( )</strong>, the compiler has no way of knowing which to choose. In this case, we have to help the compiler by using explicit function template specialization, as explained in the previous chapter<sup>.</sup></p><p>An even trickier problem is that of converting a member function into a function object suitable for using with the generic algorithms. As a simple example, suppose we have the classical "shape" problem and want to apply the <strong>draw( )</strong> member function to each pointer in a container of <strong>Shape</strong>:<sup>.</sup></p><p>//: C06:MemFun1.cpp</p><p>// Applying pointers to member functions</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../purge.h"</p><p>using namespace std;</p><empty-line/><p>class Shape {</p><p>public:</p><p>  virtual void draw() = 0;</p><p>  virtual ~Shape() {}</p><p>};</p><empty-line/><p>class Circle : public Shape {</p><p>public:</p><p>  virtual void draw() {</p><p>    cout &lt;&lt; "Circle::Draw()" &lt;&lt; endl;</p><p>  }</p><p>  ~Circle() {</p><p>    cout &lt;&lt; "Circle::~Circle()" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class Square : public Shape {</p><p>public:</p><p>  virtual void draw() {</p><p>    cout &lt;&lt; "Square::Draw()" &lt;&lt; endl;</p><p>  }</p><p>  ~Square() {</p><p>    cout &lt;&lt; "Square::~Square()" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  vector&lt;Shape*&gt; vs;</p><p>  vs.push_back(new Circle);</p><p>  vs.push_back(new Square);</p><p>  for_each(vs.begin(), vs.end(),</p><p>    mem_fun(&amp;Shape::draw));</p><p>  purge(vs);</p><p>} ///:~</p><empty-line/><p>The <strong>for_each( )</strong> algorithm does just what it sounds like it: it passes each element in a sequence to the function object denoted by its third argument. In this case, we want the function object to wrap one of the member functions of the class itself, and so the function object’s "argument" becomes the pointer to the object that the member function is called for. To produce such a function object, the <strong>mem_fun( )</strong> template takes a pointer to a member as its argument. The <strong>purge( )</strong> function is just a little something we wrote that calls delete on every element of sequence<sup>.</sup></p><p>The <strong>mem_fun( )</strong> functions are for producing function objects that are called using a pointer to the object that the member function is called for, while <strong>mem_fun_ref( )</strong> is used for calling the member function directly for an object. One set of overloads of both <strong>mem_fun( )</strong> and <strong>mem_fun_ref( )</strong> is for member functions that take zero arguments and one argument, and this is multiplied by two to handle <strong>const</strong> vs. non-<strong>const</strong> member functions. However, templates and overloading takes care of sorting all that out; all you need to remember is when to use <strong>mem_fun( )</strong> vs. <strong>mem_fun_ref( )</strong><sup><strong>.</strong></sup></p><p>Suppose you have a container of objects (not pointers), and you want to call a member function that takes an argument. The argument you pass should come from a second container of objects. To accomplish this, use the second overloaded form of the <strong>transform( )</strong> algorithm:<sup>.</sup></p><p>//: C06:MemFun2.cpp</p><p>// Calling member functions through an object reference</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>class Angle {</p><p>  int degrees;</p><p>public:</p><p>  Angle(int deg) : degrees(deg) {}</p><p>  int mul(int times) {</p><p>    return degrees *= times;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  vector&lt;Angle&gt; va;</p><p>  for(int i = 0; i &lt; 50; i += 10)</p><p>    va.push_back(Angle(i));</p><p>  int x[] = { 1, 2, 3, 4, 5 };</p><p>  transform(va.begin(), va.end(), x,</p><p>    ostream_iterator&lt;int&gt;(cout, " "),</p><p>    mem_fun_ref(&amp;Angle::mul));</p><p>  cout &lt;&lt; endl;</p><p>  // Output: 0 20 60 120 200</p><p>} ///:~</p><empty-line/><p>Because the container is holding objects, <strong>mem_fun_ref( )</strong> must be used with the pointer-to-member function. This version of <strong>transform( )</strong> takes the start and end point of the first range (where the objects live); the starting point of the second range, which holds the arguments to the member function; the destination iterator, which in this case is standard output; and the function object to call for each object. This function object is created with <strong>mem_fun_ref( )</strong> and the desired pointer to member. Notice that the <strong>transform( )</strong> and <strong>for_each( )</strong> template functions are incomplete; <strong>transform( )</strong> requires that the function it calls return a value, and there is no <strong>for_each( )</strong> that passes two arguments to the function it calls. Thus, you cannot call a member function that returns <strong>void</strong> and takes an argument using <strong>transform( )</strong> or <strong>for_each( )</strong><sup><strong>.</strong></sup></p><p>Most any member function works with <strong>mem_fun_ref( )</strong>. You can also use standard library member functions, if your compiler doesn’t add any default arguments beyond the normal arguments specified in the standard.<sup>[84]</sup> For example, suppose you’d like to read a file and search for blank lines; your compiler may allow you to use the <strong>string::empty( )</strong> member function like this:<sup>.</sup></p><p>//: C06:FindBlanks.cpp</p><p>// Demonstrates mem_fun_ref() with string::empty()</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;fstream&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>typedef vector&lt;string&gt;::iterator LSI;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  char* fname = "FindBlanks.cpp";</p><p>  if(argc &gt; 1) fname = argv[1];</p><p>  ifstream in(fname);</p><p>  assure(in, fname);</p><p>  vector&lt;string&gt; vs;</p><p>  string s;</p><p>  while(getline(in, s))</p><p>    vs.push_back(s);</p><p>  vector&lt;string&gt; cpy = vs; // For testing</p><p>  LSI lsi = find_if(vs.begin(), vs.end(),</p><p>     mem_fun_ref(&amp;string::empty));</p><p>  while(lsi != vs.end()) {</p><p>    *lsi = "A BLANK LINE";</p><p>    lsi = find_if(vs.begin(), vs.end(),</p><p>      mem_fun_ref(&amp;string::empty));</p><p>  }</p><p>  for(size_t i = 0; i &lt; cpy.size(); i++)</p><p>    if(cpy[i].size() == 0)</p><p>      assert(vs[i] == "A BLANK LINE");</p><p>    else</p><p>      assert(vs[i] != "A BLANK LINE");</p><p>} ///:~</p><empty-line/><p>This example uses <strong>find_if( )</strong> to locate the first blank line in the given range using <strong>mem_fun_ref( )</strong> with <strong>string::empty( )</strong>. After the file is opened and read into the vector, the process is repeated to find every blank line in the file. Each time a blank line is found, it is replaced with the characters "A BLANK LINE." All you have to do to accomplish this is dereference the iterator to select the current string<sup>.</sup></p></section><section><title><p>Writing your own function object adapters</p></title><p>Consider how to write a program that converts strings representing floating-point numbers to their actual numeric values. To get things started, here’s a generator that creates the strings:<sup>.</sup></p><p>//: C06:NumStringGen.h</p><p>// A random number generator that produces</p><p>// strings representing floating-point numbers</p><p>#ifndef NUMSTRINGGEN_H</p><p>#define NUMSTRINGGEN_H</p><p>#include &lt;string&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><empty-line/><p>class NumStringGen {</p><p>  const int sz; // Number of digits to make</p><p>public:</p><p>  NumStringGen(int ssz = 5) : sz(ssz) {</p><p>    std::srand(std::time(0));</p><p>  }</p><p>  std::string operator()() {</p><p>    static char n[] = "0123456789";</p><p>    const int nsz = sizeof n / sizeof *n;</p><p>    std::string r(sz, ' ');</p><p>    for(int i = 0; i &lt; sz; i++)</p><p>      if(i == sz/2)</p><p>        r[i] = '.'; // Insert a decimal point</p><p>      else</p><p>        r[i] = n[std::rand() % nsz];</p><p>    return r;</p><p>  }</p><p>};</p><p>#endif // NUMSTRINGGEN_H ///:~</p><empty-line/><p>You tell it how big the strings should be when you create the <strong>NumStringGen</strong> object. The random number generator selects digits, and a decimal point is placed in the middle<sup>.</sup></p><p>The following program uses <strong>NumStringGen</strong> to fill a <strong>vector&lt;string&gt;</strong>. However, to use the standard C library function <strong>atof( )</strong> to convert the strings to floating-point numbers, the <strong>string</strong> objects must first be turned into <strong>char</strong> pointers, since there is no automatic type conversion from <strong>string</strong> to <strong>char*</strong>. The <strong>transform( )</strong> algorithm can be used with <strong>mem_fun_ref( )</strong> and <strong>string::c_str( )</strong> to convert all the <strong>string</strong>s to <strong>char*</strong>, and then these can be transformed using <strong>atof</strong><sup><strong>.</strong></sup></p><p>//: C06:MemFun3.cpp</p><p>// Using mem_fun()</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "NumStringGen.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  const int sz = 9;</p><p>  vector&lt;string&gt; vs(sz);</p><p>  // Fill it with random number strings:</p><p>  generate(vs.begin(), vs.end(), NumStringGen());</p><p>  copy(vs.begin(), vs.end(),</p><p>    ostream_iterator&lt;string&gt;(cout, "\t"));</p><p>  cout &lt;&lt; endl;</p><p>  const char* vcp[sz];</p><p>  transform(vs.begin(), vs.end(), vcp,</p><p>    mem_fun_ref(&amp;string::c_str));</p><p>  vector&lt;double&gt; vd;</p><p>  transform(vcp, vcp + sz, back_inserter(vd),</p><p>    std::atof);</p><p>  copy(vd.begin(), vd.end(),</p><p>    ostream_iterator&lt;double&gt;(cout, "\t"));</p><p>  cout &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>This program does two transformations: one to convert strings to C-style strings (arrays of characters), and one to convert the C-style strings to numbers via <strong>atof( )</strong>. It would be nice to combine these two operations into one. After all, we can compose functions in mathematics, so why not C++?<sup>.</sup></p><p>The obvious approach takes the two functions as arguments and applies them in the proper order:</p><p>//: C06:ComposeTry.cpp</p><p>// A first attempt at implementing function composition</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;typename R, typename E, typename F1, typename F2&gt;</p><p>class unary_composer {</p><p>   F1 f1;</p><p>   F2 f2;</p><p>public:</p><p>   unary_composer(F1 fone, F2 ftwo) : f1(fone), f2(ftwo) {}</p><p>   R operator()(E x) {</p><p>      return f1(f2(x));</p><p>   }</p><p>};</p><p>template&lt;typename R, typename E, typename F1, typename F2&gt;</p><p>unary_composer&lt;R, E, F1, F2&gt; compose(F1 f1, F2 f2) {</p><p>   return unary_composer&lt;R, E, F1, F2&gt;(f1, f2);</p><p>}</p><p>int main()</p><p>{</p><p>  double x =</p><p>    compose&lt;double, const string&amp;&gt;(atof,</p><p>      mem_fun_ref(&amp;string::c_str))("12.34");</p><p>  assert(x == 12.34);</p><p>} ///:~</p><empty-line/><p>The <strong>unary_composer</strong> object in this example stores the function pointers <strong>atof</strong> and <strong>string::c_str</strong> such that the latter function is applied first when its <strong>operator( )</strong> is called. The <strong>compose( )</strong> function adapter is a convenience, so we don’t have to supply all four template arguments explicitly—<strong>F1</strong> and <strong>F2</strong> are deduced from the call<sup>.</sup></p><p>It would be much better, of course, if we didn’t have to supply any template arguments at all. This is achieved by adhering to the convention for type definitions for adaptable function objects; in other words, we will assume that the functions to be composed are adaptable. This requires that we use <strong>ptr_fun( )</strong> for <strong>atof( )</strong>. For maximum flexibility, we also make <strong>unary_composer</strong> adaptable in case it gets passed to a function adapter. The following program does so and easily solves the original problem<sup>.</sup></p><p>//: C06:ComposeFinal.cpp</p><p>// An adaptable composer</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "NumStringGen.h"</p><p>using namespace std;</p><empty-line/><p>template&lt;typename F1, typename F2&gt;</p><p>class unary_composer</p><p>  : public unary_function&lt;typename F2::argument_type,</p><p>           typename F1::result_type&gt; {</p><p>public:</p><p>   unary_composer(F1 f1, F2 f2) : f1(f1), f2(f2) {}</p><p>   typename F1::result_type</p><p>     operator()(typename F2::argument_type x) {</p><p>      return f1(f2(x));</p><p>   }</p><p>private:</p><p>   F1 f1;</p><p>   F2 f2;</p><p>};</p><p>template&lt;typename F1, typename F2&gt;</p><p>unary_composer&lt;F1, F2&gt; compose(F1 f1, F2 f2) {</p><p>   return unary_composer&lt;F1, F2&gt;(f1, f2);</p><p>}</p><p>int main() {</p><p>  const int sz = 9;</p><p>  vector&lt;string&gt; vs(sz);</p><p>  // Fill it with random number strings:</p><p>  generate(vs.begin(), vs.end(), NumStringGen());</p><p>  copy(vs.begin(), vs.end(),</p><p>    ostream_iterator&lt;string&gt;(cout, "\t"));</p><p>  cout &lt;&lt; endl;</p><p>  vector&lt;double&gt; vd;</p><p>  transform(vs.begin(), vs.end(), back_inserter(vd),</p><p>    compose(ptr_fun(atof), mem_fun_ref(&amp;string::c_str)));</p><p>  copy(vd.begin(), vd.end(),</p><p>    ostream_iterator&lt;double&gt;(cout, "\t"));</p><p>  cout &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>Once again we must use <strong>typename</strong> to let the compiler know that the member we are referring to is a nested type<sup>.</sup></p><p>Some implementations<sup>[85]</sup> support composition of function objects as an extension, and the C++ standards committee is likely to add these capabilities to the next version of standard C++<sup>.</sup></p></section></section><section><title><p>A catalog of STL algorithms</p></title><section><p>This section provides a quick reference for when you’re searching for the appropriate algorithm. We leave the full exploration of all the STL algorithms to other references (see the end of this chapter, and Appendix A), along with the more intimate details of performance, and so on. Our goal here is for you to become rapidly comfortable and facile with the algorithms, and we’ll assume you will look into the more specialized references if you need more depth of detail<sup>.</sup></p><p>Although you will often see the algorithms described using their full template declaration syntax, we’re not doing that here because you already know they are templates, and it’s quite easy to see what the template arguments are from the function declarations. The type names for the arguments provide descriptions for the types of iterators required. We think you’ll find this form is easier to read, and you can quickly find the full declaration in the template header file if for some reason you feel the need<sup>.</sup></p><p>The reason for all the fuss about iterators is to accommodate any type of container that meets the requirements in the standard library. So far we have illustrated the generic algorithms with only arrays and vectors as sequences, but in the next chapter you’ll see a broad range of data structures that support less robust iteration. For this reason, the algorithms are categorized in part by the types of iteration facilities they require<sup>.</sup></p><p>The names of the iterator classes describe the iterator type to which they must conform. There are no interface base classes to enforce these iteration operations—they are just expected to be there. If they are not, your compiler will complain. The various flavors of iterators are described briefly as follows<sup>.</sup></p><p><strong>InputIterator</strong>. An input iterator only allows <emphasis>reading</emphasis> elements of its sequence in a single, forward pass using <strong>operator++</strong> and <strong>operator*.</strong> Input iterators can also be tested with <strong>operator==</strong> and <strong>operator!=</strong>. That’s all<sup>.</sup></p><p><strong>OutputIterator</strong>. An output iterator only allows <emphasis>writing</emphasis> elements to a sequence in a single, forward pass using <strong>operator++</strong> and <strong>operator*. OutputIterator</strong>s cannot be tested with <strong>operator==</strong> and <strong>operator!=</strong>, however, because you assume that you can just keep sending elements to the destination and that you don’t have to see if the destination’s end marker was reached. That is, the container that an <strong>OutputIterator</strong> references can take an infinite number of objects, so no end-checking is necessary. This requirement is important so that an <strong>OutputIterator</strong> can be used with <strong>ostream</strong>s (via <strong>ostream_iterator</strong>), but you’ll also commonly use the "insert" iterators such as are the type of iterator returned by <strong>back_inserter( )</strong>)<sup>.</sup></p><p>There is no way to determine whether multiple <strong>InputIterators</strong> or <strong>OutputIterators</strong> point within the same range, so there is no way to us multiple such iterators in concert. Just think in terms of iterators to support <strong>istream</strong>s and <strong>ostream</strong>s, and <strong>InputIterator</strong> and <strong>OutputIterator</strong> will make perfect sense. Also note that algorithms that use <strong>InputIterators</strong> or <strong>OutputIterators</strong> put the weakest restrictions on the types of iterators they will accept, which means that you can use any "more sophisticated" type of iterator when you see <strong>InputIterator</strong> or <strong>OutputIterator</strong> used as STL algorithm template arguments<sup>.</sup></p><p><strong>ForwardIterator</strong>. Because you can only read from an <strong>InputIterator</strong> and write to an <strong>OutputIterator</strong>, you can’t use either of them to simultaneously read and modify a range, and you can’t dereference such an iterator more than once. With a <strong>ForwardIterator</strong> these restrictions are relaxed; you can still only move forward using <strong>operator++</strong>, but you can both write and read, and you can compare such iterators in the same range for equality. Since forward iterators can both read and write, they can of course be used wherever an input or output iterator is called for<sup>.</sup></p><p><strong>BidirectionalIterator</strong>. Effectively, this is a <strong>ForwardIterator</strong> that can also go backward. That is, a <strong>BidirectionalIterator</strong> supports all the operations that a <strong>ForwardIterator</strong> does, but in addition it has an <strong>operator--</strong><sup><strong>.</strong></sup></p><p><strong>RandomAccessIterator</strong>. This type of iterator supports all the operations that a regular pointer does: you can add and subtract integral values to move it forward and backward by jumps (rather than just one element at a time), you can subscript it with <strong>operator[ ]</strong>, you can subtract one iterator from another, and you can compare iterators to see which is greater using <strong>operator&lt;</strong>, <strong>operator&gt;</strong>, and so on. If you’re implementing a sorting routine or something similar, random access iterators are necessary to be able to create an efficient algorithm<sup>.</sup></p><p>The names used for the template parameter types in the algorithm descriptions later in this chapter consist of the listed iterator types (sometimes with a ‘1’ or ‘2’ appended to distinguish different template arguments) and can also include other arguments, often function objects<sup>.</sup></p><p>When describing the group of elements that an operation is performed on, mathematical "range" notation is often used. In this, the square bracket means "includes the end point," and the parenthesis means "does not include the end point." When using iterators, a range is determined by the iterator pointing to the initial element and by the "past-the-end" iterator, pointing past the last element. Since the past-the-end element is never used, the range determined by a pair of iterators can thus be expressed as <strong>[first, last)</strong>, in which <strong>first</strong> is the iterator pointing to the initial element, and <strong>last</strong> is the past-the-end iterator<sup>.</sup></p><p>Most books and discussions of the STL algorithms arrange them according to side-effects: <emphasis>non-mutating</emphasis> algorithms don’t change the elements in the range, <emphasis>mutating</emphasis> algorithms do change the elements, and so on. These descriptions are based primarily on the underlying behavior or implementation of the algorithm—that is, on the designer’s perspective. In practice, we don’t find this a useful categorization, so instead we’ll organize them according to the problem you want to solve: are you searching for an element or set of elements, performing an operation on each element, counting elements, replacing elements, and so on. This should help you find the algorithm you want more easily<sup>.</sup></p><p>Note that all the algorithms are in the namespace <strong>std</strong>. If you do not see a different header such as <strong>&lt;utility&gt;</strong> or <strong>&lt;numeric&gt;</strong> above the function declarations, it appears in <strong>&lt;algorithm&gt;</strong>.</p></section><section><title><p>Support tools for example creation</p></title><p>It’s useful to create some basic tools with which to test the algorithms. In the examples that follow we’ll use the generators mentioned earlier in <strong>Generators.h</strong>, as well as what appears below<sup>.</sup></p><p>Displaying a range is something that will be done constantly, so here is a templatized function that let you print any sequence, regardless of the type in that sequence:<sup>.</sup></p><p>//: C06:PrintSequence.h</p><p>// Prints the contents of any sequence</p><p>#ifndef PRINTSEQUENCE_H</p><p>#define PRINTSEQUENCE_H</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><empty-line/><p>template&lt;typename InputIter&gt;</p><p>void print(InputIter first, InputIter last,</p><p>  char* nm = "", char* sep = "\n",</p><p>  std::ostream&amp; os = std::cout) {</p><p>  if(nm != 0 &amp;&amp; *nm != '\0')</p><p>    os &lt;&lt; nm &lt;&lt; ": " &lt;&lt; sep;</p><p>  while(first != last)</p><p>    os &lt;&lt; *first++ &lt;&lt; sep;</p><p>  os &lt;&lt; std::endl;</p><p>}</p><p>#endif // PRINTSEQUENCE_H ///:~</p><empty-line/><p>The default prints to <strong>cout</strong> with newlines as separators, but you can change that. You can also provide a message to print at the head of the output<sup>.</sup></p><p>Finally, a number of the STL algorithms that move elements of a sequence around distinguish between "stable" and "unstable" reordering of a sequence. This refers to preserving the original relative order of those elements that are equivalent as far as the comparison function is concerned. For example, consider a sequence <strong>{ c(1), b(1), c(2), a(1), b(2), a(2) }</strong>. These elements are tested for equivalence based on their letters, but their numbers indicate how they first appeared in the sequence. If you sort (for example) this sequence using an unstable sort, there’s no guarantee of any particular order among equivalent letters, so you could end up with <strong>{ a(2), a(1), b(1), b(2), c(2), c(1) }</strong>. However, if you use a stable sort, you will get <strong>{ a(1), a(2), b(1), b(2), c(1), c(2) }</strong>. The STL <strong>sort( )</strong> algorithm uses a variation of <emphasis>quicksort</emphasis> and is therefore unstable, but a <strong>stable_sort( )</strong> is also provided.<sup>[86]</sup></p><p>To demonstrate the stability versus instability of algorithms that reorder a sequence, we need some way to keep track of how the elements originally appeared. The following is a kind of <strong>string</strong> object that keeps track of the order in which that particular object originally appeared, using a <strong>static map</strong> that maps <strong>NString</strong>s to <strong>Counter</strong>s. Each <strong>NString</strong> then contains an <strong>occurrence</strong> field that indicates the order in which this <strong>NString</strong> was discovered<sup>.</sup></p><p>//: C06:NString.h</p><p>// A "numbered string" that indicates which</p><p>// occurrence this is of a particular word</p><p>#ifndef NSTRING_H</p><p>#define NSTRING_H</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;utility&gt;</p><p>#include &lt;vector&gt;</p><p>typedef std::pair&lt;std::string, int&gt; psi;</p><empty-line/><p>// Only compare on the first element</p><p>bool operator==(const psi&amp; l, const psi&amp; r) {</p><p>  return l.first == r.first;</p><p>}</p><empty-line/><p>class NString {</p><p>  std::string s;</p><p>  int thisOccurrence;</p><p>  // Keep track of the number of occurrences:</p><p>  typedef std::vector&lt;psi&gt; vp;</p><p>  typedef vp::iterator vpit;</p><p>  static vp words;</p><p>  void addString(const std::string&amp; x) {</p><p>    psi p(x, 0);</p><p>    vpit it = std::find(words.begin(), words.end(), p);</p><p>    if(it != words.end())</p><p>      thisOccurrence = ++it-&gt;second;</p><p>    else {</p><p>      thisOccurrence = 0;</p><p>      words.push_back(p);</p><p>    }</p><p>  }</p><p>public:</p><p>  NString() : thisOccurrence(0) {}</p><p>  NString(const std::string&amp; x) : s(x) {</p><p>    addString(x);</p><p>  }</p><p>  NString(const char* x) : s(x) {</p><p>    addString(x);</p><p>  }</p><p>  // The implicit operator= and</p><p>  // copy-constructor are OK here</p><p>  friend std::ostream&amp; operator&lt;&lt;(</p><p>    std::ostream&amp; os, const NString&amp; ns) {</p><p>    return os &lt;&lt; ns.s &lt;&lt; " ["</p><p>      &lt;&lt; ns.thisOccurrence &lt;&lt; "]";</p><p>  }</p><p>  // Need this for sorting. Notice it only</p><p>  // compares strings, not occurrences:</p><p>  friend bool</p><p>  operator&lt;(const NString&amp; l, const NString&amp; r) {</p><p>    return l.s &lt; r.s;</p><p>  }</p><p>  friend</p><p>  bool operator==(const NString&amp; l, const NString&amp; r) {</p><p>    return l.s == r.s;</p><p>  }</p><p>  // For sorting with greater&lt;NString&gt;:</p><p>  friend bool</p><p>  operator&gt;(const NString&amp; l, const NString&amp; r) {</p><p>    return l.s &gt; r.s;</p><p>  }</p><p>  // To get at the string directly:</p><p>  operator const std::string&amp;() const {return s;}</p><p>};</p><empty-line/><p>// Allocate static member object. Done here for</p><p>// brevity, but should normally be done in a</p><p>// separate cpp file:</p><p>NString::vp NString::words;</p><p>#endif // NSTRING_H ///:~</p><empty-line/><p>We would normally use a <strong>map</strong> container to associate a string with its number of occurrences, but maps don’t appear until the next chapter, so we use a <strong>vector</strong> of pairs instead. You’ll see plenty of similar examples there<sup>.</sup></p><p>To do an ordinary ascending sort, the only operator that’s necessary is <strong>NString::operator&lt;( )</strong>; however, to sort in reverse order, the <strong>operator&gt;( )</strong> is also provided so that the <strong>greater</strong> template can call it<sup>.</sup></p><p>As this is just a demonstration class, we are taking the liberty of placing the definition of the static members <strong>words</strong> and <strong>occurrences</strong> in this header file, but this will break down if the header file is included in more than one place, so you should normally place all <strong>static</strong> definitions in <strong>cpp</strong> files<sup>.</sup></p></section><section><title><p>Filling and generating</p></title><section><p>These algorithms let you automatically fill a range with a particular value or generate a set of values for a particular range. The "fill" functions insert a single value multiple times into the container, and the "generate" functions use an object called a <emphasis>generator</emphasis> (described earlier) to create the values to insert into the container<sup>.</sup></p><p>void <strong>fill</strong>(ForwardIterator first, ForwardIterator last, const T&amp; value); void <strong>fill_n</strong>(OutputIterator first, Size n, const T&amp; value);</p><p><strong>fill( )</strong> assigns <strong>value</strong> to every element in the range <strong>[first, last)</strong>. <strong>fill_n( )</strong> assigns <strong>value</strong> to <strong>n</strong> elements starting at <strong>first</strong><sup><strong>.</strong></sup></p><p>void <strong>generate</strong>(ForwardIterator first, ForwardIterator last, Generator gen); void <strong>generate_n</strong>(OutputIterator first, Size n, Generator gen);</p><p><strong>generate( )</strong> makes a call to <strong>gen( )</strong> for each element in the range <strong>[first, last)</strong>, presumably to produce a different value for each element. <strong>generate_n( )</strong> calls <strong>gen( ) n</strong> times and assigns each result to <strong>n</strong> elements starting at <strong>first</strong><sup><strong>.</strong></sup></p></section><section><section><title><p>Example</p></title><p>The following example fills and generates into <strong>vector</strong>s. It also shows the use of <strong>print( )</strong>:</p><p>//: C06:FillGenerateTest.cpp</p><p>// Demonstrates "fill" and "generate"</p><p>#include "Generators.h"</p><p>#include "PrintSequence.h"</p><p>#include &lt;vector&gt;</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  vector&lt;string&gt; v1(5);</p><p>  fill(v1.begin(), v1.end(), "howdy");</p><p>  print(v1.begin(), v1.end(), "v1", " ");</p><p>  vector&lt;string&gt; v2;</p><p>  fill_n(back_inserter(v2), 7, "bye");</p><p>  print(v2.begin(), v2.end(), "v2");</p><p>  vector&lt;int&gt; v3(10);</p><p>  generate(v3.begin(), v3.end(), SkipGen(4,5));</p><p>  print(v3.begin(), v3.end(), "v3", " ");</p><p>  vector&lt;int&gt; v4;</p><p>  generate_n(back_inserter(v4),15, URandGen(30));</p><p>  print(v4.begin(), v4.end(), "v4", " ");</p><p>} ///:~</p><empty-line/><p>A <strong>vector&lt;string&gt;</strong> is created with a predefined size. Since storage has already been created for all the <strong>string</strong> objects in the <strong>vector</strong>, <strong>fill( )</strong> can use its assignment operator to assign a copy of "howdy" to each space in the <strong>vector</strong>. Also, the default newline separator is replaced with a space<sup>.</sup></p><p>The second <strong>vector&lt;string&gt; v2</strong> is not given an initial size, so <strong>back_inserter</strong> must be used to force new elements in instead of trying to assign to existing locations. Just as an example, the other <strong>print( )</strong> is used, which requires a range<sup>.</sup></p><p>The <strong>generate( )</strong> and <strong>generate_n( )</strong> functions have the same form as the "fill" functions except that they use a generator instead of a constant value; here, both generators are demonstrated<sup>.</sup></p></section></section></section><section><title><p>Counting</p></title><section><p>All containers have a member function <strong>size( )</strong> that will tells you how many elements they hold. The return type of <strong>size( )</strong> is the iterator’s <strong>difference_type</strong><sup>[87]</sup> (usually <strong>ptrdiff_t</strong>), which we denote by <strong>IntegralValue</strong> in the following. The following two algorithms count objects that satisfy certain criteria<sup>.</sup></p><p>IntegralValue <strong>count</strong>(InputIterator first, InputIterator last, const EqualityComparable&amp; value);</p><p>Produces the number of elements in <strong>[first, last)</strong> that are equivalent to <strong>value</strong> (when tested using <strong>operator==</strong>).</p><p>IntegralValue <strong>count_if</strong>(InputIterator first, InputIterator last, Predicate pred);</p><p>Produces the number of elements in <strong>[first, last)</strong> that each cause <strong>pred</strong> to return <strong>true</strong><sup><strong>.</strong></sup></p></section><section><section><title><p>Example</p></title><p>Here, a <strong>vector&lt;char&gt; v</strong> is filled with random characters (including some duplicates). A <strong>set&lt;char&gt;</strong> is initialized from <strong>v</strong>, so it holds only one of each letter represented in <strong>v</strong>. This <strong>set</strong> counts all the instances of all the characters, which are then displayed:<sup>.</sup></p><p>//: C06:Counting.cpp</p><p>// The counting algorithms</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;set&gt;</p><p>#include &lt;vector&gt;</p><p>#include "Generators.h"</p><p>#include "PrintSequence.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  vector&lt;char&gt; v;</p><p>  generate_n(back_inserter(v), 50, CharGen());</p><p>  print(v.begin(), v.end(), "v", "");</p><p>  // Create a set of the characters in v:</p><p>  set&lt;char&gt; cs(v.begin(), v.end());</p><p>  typedef set&lt;char&gt;::iterator sci;</p><p>  for(sci it = cs.begin(); it != cs.end(); it++) {</p><p>    int n = count(v.begin(), v.end(), *it);</p><p>    cout &lt;&lt; *it &lt;&lt; ": " &lt;&lt; n &lt;&lt; ", ";</p><p>  }</p><p>  int lc = count_if(v.begin(), v.end(),</p><p>    bind2nd(greater&lt;char&gt;(), 'a'));</p><p>  cout &lt;&lt; "\nLowercase letters: " &lt;&lt; lc &lt;&lt; endl;</p><p>  sort(v.begin(), v.end());</p><p>  print(v.begin(), v.end(), "sorted", "");</p><p>} ///:~</p><empty-line/><p>The <strong>count_if( )</strong> algorithm is demonstrated by counting all the lowercase letters; the predicate is created using the <strong>bind2nd( )</strong> and <strong>greater</strong> function object templates<sup>.</sup></p></section></section></section><section><title><p>Manipulating sequences</p></title><section><p>These algorithms let you move sequences around<sup>.</sup></p><p>OutputIterator <strong>copy</strong>(InputIterator first, InputIterator last, OutputIterator destination);</p><p>Using assignment, copies from <strong>[first, last)</strong> to <strong>destination</strong>, incrementing <strong>destination</strong> after each assignment. This is essentially a "shuffle-left" operation, and so the source sequence must not contain the destination. Because assignment is used, you cannot directly insert elements into an empty container or at the end of a container, but instead you must wrap the <strong>destination</strong> iterator in an <strong>insert_iterator</strong> (typically by using <strong>back_inserter( )</strong> or by using <strong>inserter( )</strong> in the case of an associative container)<sup>.</sup></p><p>BidirectionalIterator2 <strong>copy_backward</strong>(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 destinationEnd);</p><p>Like <strong>copy( )</strong>, but actually copies the elements in reverse order. This is essentially a "shuffle-right" operation, and, like <strong>copy( )</strong>, the source sequence must not contain the destination. The source range <strong>[first, last)</strong> is copied to the destination, but the first destination element is <strong>destinationEnd - 1</strong>. This iterator is then decremented after each assignment. The space in the destination range must already exist (to allow assignment), and the destination range cannot be within the source range<sup>.</sup></p><p>void <strong>reverse</strong>(BidirectionalIterator first, BidirectionalIterator last); OutputIterator <strong>reverse_copy</strong>(BidirectionalIterator first, BidirectionalIterator last, OutputIterator destination);</p><p>Both forms of this function reverse the range <strong>[first, last)</strong>. <strong>reverse( )</strong> reverses the range in place, and <strong>reverse_copy( )</strong> leaves the original range alone and copies the reversed elements into <strong>destination</strong>, returning the past-the-end iterator of the resulting range<sup>.</sup></p><p>ForwardIterator2 <strong>swap_ranges</strong>(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2);</p><p>Exchanges the contents of two ranges of equal size by swapping corresponding elements<sup>.</sup></p><p>void <strong>rotate</strong>(ForwardIterator first, ForwardIterator middle, ForwardIterator last); OutputIterator <strong>rotate_copy</strong>(ForwardIterator first, ForwardIterator middle, ForwardIterator last, OutputIterator destination);</p><p>Moves the contents of <strong>[first, middle)</strong> to the end of the sequence, and the contents of <strong>[middle, last)</strong> to the beginning. With <strong>rotate( )</strong>, the swap is performed in place; and with <strong>rotate_copy( )</strong> the original range is untouched, and the rotated version is copied into <strong>destination</strong>, returning the past-the-end iterator of the resulting range. Note that while <strong>swap_ranges( )</strong> requires that the two ranges be exactly the same size, the "rotate" functions do not<sup>.</sup></p><p>bool <strong>next_permutation</strong>(BidirectionalIterator first, BidirectionalIterator last); bool <strong>next_permutation</strong>(BidirectionalIterator first, BidirectionalIterator last, StrictWeakOrdering binary_pred); bool <strong>prev_permutation</strong>(BidirectionalIterator first, BidirectionalIterator last); bool <strong>prev_permutation</strong>(BidirectionalIterator first, BidirectionalIterator last, StrictWeakOrdering binary_pred);</p><p>A <emphasis>permutation</emphasis> is one unique ordering of a set of elements. If you have <strong>n</strong> unique elements, there are <strong>n!</strong> (<strong>n</strong> factorial) distinct possible combinations of those elements. All these combinations can be conceptually sorted into a sequence using a lexicographical (dictionary-like) ordering and thus produce a concept of a "next" and "previous" permutation. Therefore, whatever the current ordering of elements in the range, there is a distinct "next" and "previous" permutation in the sequence of permutations<sup>.</sup></p><p>The <strong>next_permutation( )</strong> and <strong>prev_permutation( )</strong> functions rearrange the elements into their next or previous permutation and if successful return <strong>true</strong>. If there are no more "next" permutations, the elements are in sorted order; so <strong>next_permutation( )</strong> returns <strong>false</strong>. If there are no more "previous" permutations, the elements are in descending sorted order; so <strong>previous_permutation( )</strong> returns <strong>false</strong><sup><strong>.</strong></sup></p><p>The versions of the functions that have a <strong>StrictWeakOrdering</strong> argument perform the comparisons using <strong>binary_pred</strong> instead of <strong>operator&lt;</strong>.</p><p>void <strong>random_shuffle</strong>(RandomAccessIterator first, RandomAccessIterator last); void <strong>random_shuffle</strong>(RandomAccessIterator first, RandomAccessIterator last RandomNumberGenerator&amp; rand);</p><p>This function randomly rearranges the elements in the range. It yields uniformly distributed results if the random-number generator does. The first form uses an internal random number generator, and the second uses a user-supplied random-number generator. The generator must return a value in the range [0, n) for some positive n<sup>.</sup></p><p>BidirectionalIterator <strong>partition</strong>(BidirectionalIterator first, BidirectionalIterator last, Predicate pred); BidirectionalIterator <strong>stable_partition</strong>(BidirectionalIterator first,   BidirectionalIterator last, Predicate pred);</p><p>The "partition" functions move elements that satisfy <strong>pred</strong> to the beginning of the sequence. An iterator pointing one past the last of those elements is returned (which is, in effect, and "end" iterator" for the initial subsequence of elements that satisfy <strong>pred</strong>). This location is often called the "partition point"<sup>.</sup></p><p>With <strong>partition( )</strong>, the order of the elements in each resulting subsequence after the function call is not specified, but with <strong>stable_parition( ),</strong> the relative order of the elements before and after the partition point will be the same as before the partitioning process<sup>.</sup></p></section><section><section><title><p>Example</p></title><p>This gives a basic demonstration of sequence manipulation:<sup>.</sup></p><p>//: C06:Manipulations.cpp</p><p>// Shows basic manipulations</p><p>#include "PrintSequence.h"</p><p>#include "NString.h"</p><p>#include "Generators.h"</p><p>#include &lt;vector&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;algorithm&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  vector&lt;int&gt; v1(10);</p><p>  // Simple counting:</p><p>  generate(v1.begin(), v1.end(), SkipGen());</p><p>  print(v1.begin(), v1.end(), "v1", " ");</p><p>  vector&lt;int&gt; v2(v1.size());</p><p>  copy_backward(v1.begin(), v1.end(), v2.end());</p><p>  print(v2.begin(), v2.end(), "copy_backward", " ");</p><p>  reverse_copy(v1.begin(), v1.end(), v2.begin());</p><p>  print(v2.begin(), v2.end(), "reverse_copy", " ");</p><p>  reverse(v1.begin(), v1.end());</p><p>  print(v1.begin(), v1.end(), "reverse", " ");</p><p>  int half = v1.size() / 2;</p><p>  // Ranges must be exactly the same size:</p><p>  swap_ranges(v1.begin(), v1.begin() + half,</p><p>    v1.begin() + half);</p><p>  print(v1.begin(), v1.end(), "swap_ranges", " ");</p><p>  // Start with fresh sequence:</p><p>  generate(v1.begin(), v1.end(), SkipGen());</p><p>  print(v1.begin(), v1.end(), "v1", " ");</p><p>  int third = v1.size() / 3;</p><p>  for(int i = 0; i &lt; 10; i++) {</p><p>    rotate(v1.begin(), v1.begin() + third,</p><p>      v1.end());</p><p>    print(v1.begin(), v1.end(), "rotate", " ");</p><p>  }</p><p>  cout &lt;&lt; "Second rotate example:" &lt;&lt; endl;</p><p>  char c[] = "aabbccddeeffgghhiijj";</p><p>  const char csz = strlen(c);</p><p>  for(int i = 0; i &lt; 10; i++) {</p><p>    rotate(c, c + 2, c + csz);</p><p>    print(c, c + csz, "", "");</p><p>  }</p><p>  cout &lt;&lt; "All n! permutations of abcd:" &lt;&lt; endl;</p><p>  int nf = 4 * 3 * 2 * 1;</p><p>  char p[] = "abcd";</p><p>  for(int i = 0; i &lt; nf; i++) {</p><p>    next_permutation(p, p + 4);</p><p>    print(p, p + 4, "", "");</p><p>  }</p><p>  cout &lt;&lt; "Using prev_permutation:" &lt;&lt; endl;</p><p>  for(int i = 0; i &lt; nf; i++) {</p><p>    prev_permutation(p, p + 4);</p><p>    print(p, p + 4, "", "");</p><p>  }</p><p>  cout &lt;&lt; "random_shuffling a word:" &lt;&lt; endl;</p><p>  string s("hello");</p><p>  cout &lt;&lt; s &lt;&lt; endl;</p><p>  for(int i = 0; i &lt; 5; i++) {</p><p>    random_shuffle(s.begin(), s.end());</p><p>    cout &lt;&lt; s &lt;&lt; endl;</p><p>  }</p><p>  NString sa[] = { "a", "b", "c", "d", "a", "b",</p><p>    "c", "d", "a", "b", "c", "d", "a", "b", "c"};</p><p>  const int sasz = sizeof sa / sizeof *sa;</p><p>  vector&lt;NString&gt; ns(sa, sa + sasz);</p><p>  print(ns.begin(), ns.end(), "ns", " ");</p><p>  vector&lt;NString&gt;::iterator it =</p><p>    partition(ns.begin(), ns.end(),</p><p>      bind2nd(greater&lt;NString&gt;(), "b"));</p><p>  cout &lt;&lt; "Partition point: " &lt;&lt; *it &lt;&lt; endl;</p><p>  print(ns.begin(), ns.end(), "", " ");</p><p>  // Reload vector:</p><p>  copy (sa, sa + sasz, ns.begin());</p><p>  it = stable_partition(ns.begin(), ns.end(),</p><p>    bind2nd(greater&lt;NString&gt;(), "b"));</p><p>  cout &lt;&lt; "Stable partition" &lt;&lt; endl;</p><p>  cout &lt;&lt; "Partition point: " &lt;&lt; *it &lt;&lt; endl;</p><p>  print(ns.begin(), ns.end(), "", " ");</p><p>} ///:~</p><empty-line/><p>The best way to see the results of this program is to run it. (You’ll probably want to redirect the output to a file.)</p><p>The <strong>vector&lt;int&gt; v1</strong> is initially loaded with a simple ascending sequence and printed. You’ll see that the effect of <strong>copy_backward( )</strong> (which copies into <strong>v2</strong>, which is the same size as <strong>v1</strong>) is the same as an ordinary copy. Again, <strong>copy_backward( )</strong> does the same thing as <strong>copy( )</strong>; it just performs the operations in reverse order<sup>.</sup></p><p><strong>reverse_copy( )</strong>, however, actually does create a reversed copy, and <strong>reverse( )</strong> performs the reversal in place. Next, <strong>swap_ranges( )</strong> swaps the upper half of the reversed sequence with the lower half. Of course, the ranges could be smaller subsets of the entire vector, as long as they are of equivalent size<sup>.</sup></p><p>After re-creating the ascending sequence, <strong>rotate( )</strong> is demonstrated by rotating one third of <strong>v1</strong> multiple times. A second <strong>rotate( )</strong> example uses characters and just rotates two characters at a time. This also demonstrates the flexibility of both the STL algorithms and the <strong>print( )</strong> template, since they can both be used with arrays of <strong>char</strong> as easily as with anything else<sup>.</sup></p><p>To demonstrate <strong>next_permutation( )</strong> and <strong>prev_permutation( )</strong>, a set of four characters "abcd" is permuted through all <strong>n!</strong> (<strong>n</strong> factorial) possible combinations. You’ll see from the output that the permutations move through a strictly defined order (that is, permuting is a deterministic process).</p><p>A quick-and-dirty demonstration of <strong>random_shuffle( )</strong> is to apply it to a <strong>string</strong> and see what words result. Because a <strong>string</strong> object has <strong>begin( )</strong> and <strong>end( )</strong> member functions that return the appropriate iterators, it too can be easily used with many of the STL algorithms. Of course, an array of <strong>char</strong> could also have been used<sup>.</sup></p><p>Finally, the <strong>partition( )</strong> and <strong>stable_partition( )</strong> are demonstrated, using an array of <strong>NString</strong>. You’ll note that the aggregate initialization expression uses <strong>char</strong> arrays, but <strong>NString</strong> has a <strong>char*</strong> constructor that is automatically used<sup>.</sup></p><p>You’ll see from the output that with the unstable partition, the objects are correctly above and below the partition point, but in no particular order; whereas with the stable partition, their original order is maintained.</p></section></section></section><section><title><p>Searching and replacing</p></title><section><p>All these algorithms are used for searching for one or more objects within a range defined by the first two iterator arguments<sup>.</sup></p><p>InputIterator <strong>find</strong>(InputIterator first, InputIterator last,   const EqualityComparable&amp; value);</p><p>Searches for <strong>value </strong>within a range of elements. Returns an iterator in the range <strong>[first, last)</strong> that points to the first occurrence of <strong>value</strong>. If <strong>value</strong> isn’t in the range, <strong>find( )</strong> returns <strong>last</strong>. This is a <emphasis>linear search</emphasis>; that is, it starts at the beginning and looks at each sequential element without making any assumptions about the way the elements are ordered. In contrast, a <strong>binary_search( )</strong> (defined later) works on a sorted sequence and can thus be much faster.</p><p>InputIterator <strong>find_if</strong>(InputIterator first, InputIterator   last, Predicate pred);</p><p>Just like <strong>find( )</strong>, <strong>find_if( )</strong> performs a linear search through the range. However, instead of searching for <strong>value</strong>, <strong>find_if( )</strong> looks for an element such that the <strong>Predicate pred</strong> returns <strong>true</strong> when applied to that element. Returns <strong>last</strong> if no such element can be found<sup>.</sup></p><p>ForwardIterator <strong>adjacent_find</strong>(ForwardIterator first,   ForwardIterator last); ForwardIterator <strong>adjacent_find</strong>(ForwardIterator first,   ForwardIterator last, BinaryPredicate binary_pred);</p><p>Like <strong>find( )</strong>, performs a linear search through the range, but instead of looking for only one element, it searches for two adjacent elements that are equivalent. The first form of the function looks for two elements that are equivalent (via <strong>operator==</strong>). The second form looks for two adjacent elements that, when passed together to <strong>binary_pred</strong>, produce a <strong>true</strong> result. An iterator to the first of the two elements is returned if a pair is found; otherwise, <strong>last</strong> is returned.</p><p>ForwardIterator1 <strong>find_first_of</strong>(ForwardIterator1 first1,   ForwardIterator1 last1, ForwardIterator2 first2,   ForwardIterator2 last2); ForwardIterator1 <strong>find_first_of</strong>(ForwardIterator1 first1,   ForwardIterator1 last1, ForwardIterator2 first2,   ForwardIterator2 last2, BinaryPredicate binary_pred);<sup>.</sup></p><p>Like <strong>find( )</strong>, performs a linear search through the range. Both forms search for an element in the second range that’s equivalent to one in the first, the first form using <strong>operator==</strong>, and the second using the supplied predicate. In the second form, the current element from the first range becomes the first argument to <strong>binary_pred</strong>, and the element from the second range becomes the second argument. </p><p>ForwardIterator1 <strong>search</strong>(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); ForwardIterator1 <strong>search</strong>(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2 BinaryPredicate binary_pred);</p><p>Checks to see if the second range occurs (in the exact order of the second range) within the first range, and if so returns an iterator pointing to the place in the first range where the second range begins. Returns <strong>last1</strong> if no subset can be found. The first form performs its test using <strong>operator==</strong>, and the second checks to see if each pair of objects being compared causes <strong>binary_pred</strong> to return <strong>true</strong>. </p><p>ForwardIterator1 <strong>find_end</strong>(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); ForwardIterator1 <strong>find_end</strong>(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate binary_pred);</p><p>The forms and arguments are just like <strong>search( )</strong> in that they look for the second range appearing as a subset of the first range, but while <strong>search( )</strong> looks for the first occurrence of the subset, <strong>find_end( )</strong> looks for the <emphasis>last</emphasis> occurrence and returns an iterator to its first element<sup>.</sup></p><p>ForwardIterator <strong>search_n</strong>(ForwardIterator first, ForwardIterator last, Size count, const T&amp; value); ForwardIterator <strong>search_n</strong>(ForwardIterator first, ForwardIterator last, Size count, const T&amp; value, BinaryPredicate binary_pred);</p><p>Looks for a group of <strong>count</strong> consecutive values in <strong>[first, last)</strong> that are all equal to <strong>value</strong> (in the first form) or that all cause a return value of <strong>true</strong> when passed into <strong>binary_pred</strong> along with <strong>value</strong> (in the second form). Returns <strong>last</strong> if such a group cannot be found. </p><p>ForwardIterator <strong>min_element</strong>(ForwardIterator first, ForwardIterator last); ForwardIterator <strong>min_element</strong>(ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred);</p><p>Returns an iterator pointing to the first occurrence of the "smallest" value in the range (as explained below—there may be multiple occurrences of this value.) Returns <strong>last</strong> if the range is empty. The first version performs comparisons with <strong>operator&lt;,</strong> and the value <strong>r </strong>returned is such that *<strong>e &lt; *r</strong> is false for every element <strong>e</strong> in the range <strong>[first, r)</strong>. The second version compares using <strong>binary_pred,</strong> and the value <strong>r</strong> returned is such that <strong>binary_pred (*e, *r)</strong> is false for every element <strong>e</strong> in the range <strong>[first, r)</strong>.</p><p>ForwardIterator <strong>max_element</strong>(ForwardIterator first, ForwardIterator last); ForwardIterator <strong>max_element</strong>(ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred);</p><p>Returns an iterator pointing to the first occurrence of the largest value in the range. (There may be multiple occurrences of the largest value.) Returns <strong>last</strong> if the range is empty. The first version performs comparisons with <strong>operator&lt;,</strong> and the value <strong>r </strong>returned is such that *<strong>r &lt; *e</strong> is false for every element <strong>e</strong> in the range <strong>[first, r)</strong>. The second version compares using <strong>binary_pred,</strong> and the value <strong>r</strong> returned is such that <strong>binary_pred (*r, *e)</strong> is false for every element <strong>e</strong> in the range <strong>[first, r)</strong>.</p><p>void <strong>replace</strong>(ForwardIterator first, ForwardIterator last, const T&amp; old_value, const T&amp; new_value); void <strong>replace_if</strong>(ForwardIterator first, ForwardIterator last, Predicate pred, const T&amp; new_value); OutputIterator <strong>replace_copy</strong>(InputIterator first, InputIterator last, OutputIterator result, const T&amp; old_value, const T&amp; new_value); OutputIterator <strong>replace_copy_if</strong>(InputIterator first, InputIterator last, OutputIterator result, Predicate pred, const T&amp; new_value);</p><p>Each of the "replace" forms moves through the range <strong>[first, last)</strong>, finding values that match a criterion and replacing them with <strong>new_value</strong>. Both <strong>replace( )</strong> and <strong>replace_copy( )</strong> simply look for <strong>old_value</strong> to replace; <strong>replace_if( )</strong> and <strong>replace_copy_if( )</strong> look for values that satisfy the predicate <strong>pred</strong>. The "copy" versions of the functions do not modify the original range but instead make a copy with the replacements into <strong>result</strong> (incrementing <strong>result</strong> after each assignment).</p></section><section><section><title><p>Example</p></title><p>To provide easy viewing of the results, this example manipulates <strong>vector</strong>s of <strong>int</strong>. Again, not every possible version of each algorithm is shown. (Some that should be obvious have been omitted.)</p><p>//: C06:SearchReplace.cpp</p><p>// The STL search and replace algorithms</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;vector&gt;</p><p>#include "PrintSequence.h"</p><p>using namespace std;</p><empty-line/><p>struct PlusOne {</p><p>  bool operator()(int i, int j) {</p><p>    return j == i + 1;</p><p>  }</p><p>};</p><empty-line/><p>class MulMoreThan {</p><p>  int value;</p><p>public:</p><p>  MulMoreThan(int val) : value(val) {}</p><p>  bool operator()(int v, int m) {</p><p>    return v * m &gt; value;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  int a[] = { 1, 2, 3, 4, 5, 6, 6, 7, 7, 7,</p><p>    8, 8, 8, 8, 11, 11, 11, 11, 11 };</p><p>  const int asz = sizeof a / sizeof *a;</p><p>  vector&lt;int&gt; v(a, a + asz);</p><p>  print(v.begin(), v.end(), "v", " ");</p><p>  vector&lt;int&gt;::iterator it =</p><p>    find(v.begin(), v.end(), 4);</p><p>  cout &lt;&lt; "find: " &lt;&lt; *it &lt;&lt; endl;</p><p>  it = find_if(v.begin(), v.end(),</p><p>    bind2nd(greater&lt;int&gt;(), 8));</p><p>  cout &lt;&lt; "find_if: " &lt;&lt; *it &lt;&lt; endl;</p><p>  it = adjacent_find(v.begin(), v.end());</p><p>  while(it != v.end()) {</p><p>    cout &lt;&lt; "adjacent_find: " &lt;&lt; *it</p><p>      &lt;&lt; ", " &lt;&lt; *(it + 1) &lt;&lt; endl;</p><p>    it = adjacent_find(it + 1, v.end());</p><p>  }</p><p>  it = adjacent_find(v.begin(), v.end(),</p><p>    PlusOne());</p><p>  while(it != v.end()) {</p><p>    cout &lt;&lt; "adjacent_find PlusOne: " &lt;&lt; *it</p><p>      &lt;&lt; ", " &lt;&lt; *(it + 1) &lt;&lt; endl;</p><p>    it = adjacent_find(it + 1, v.end(),</p><p>      PlusOne());</p><p>  }</p><p>  int b[] = { 8, 11 };</p><p>  const int bsz = sizeof b / sizeof *b;</p><p>  print(b, b + bsz, "b", " ");</p><p>  it = find_first_of(v.begin(), v.end(),</p><p>    b, b + bsz);</p><p>  print(it, it + bsz, "find_first_of", " ");</p><p>  it = find_first_of(v.begin(), v.end(),</p><p>    b, b + bsz, PlusOne());</p><p>  print(it,it + bsz,"find_first_of PlusOne"," ");</p><p>  it = search(v.begin(), v.end(), b, b + bsz);</p><p>  print(it, it + bsz, "search", " ");</p><p>  int c[] = { 5, 6, 7 };</p><p>  const int csz = sizeof c / sizeof *c;</p><p>  print(c, c + csz, "c", " ");</p><p>  it = search(v.begin(), v.end(),</p><p>    c, c + csz, PlusOne());</p><p>  print(it, it + csz,"search PlusOne", " ");</p><p>  int d[] = { 11, 11, 11 };</p><p>  const int dsz = sizeof d / sizeof *d;</p><p>  print(d, d + dsz, "d", " ");</p><p>  it = find_end(v.begin(), v.end(), d, d + dsz);</p><p>  print(it, v.end(),"find_end", " ");</p><p>  int e[] = { 9, 9 };</p><p>  print(e, e + 2, "e", " ");</p><p>  it = find_end(v.begin(), v.end(),</p><p>    e, e + 2, PlusOne());</p><p>  print(it, v.end(),"find_end PlusOne"," ");</p><p>  it = search_n(v.begin(), v.end(), 3, 7);</p><p>  print(it, it + 3, "search_n 3, 7", " ");</p><p>  it = search_n(v.begin(), v.end(),</p><p>    6, 15, MulMoreThan(100));</p><p>  print(it, it + 6,</p><p>    "search_n 6, 15, MulMoreThan(100)", " ");</p><p>  cout &lt;&lt; "min_element: " &lt;&lt;</p><p>    *min_element(v.begin(), v.end()) &lt;&lt; endl;</p><p>  cout &lt;&lt; "max_element: " &lt;&lt;</p><p>    *max_element(v.begin(), v.end()) &lt;&lt; endl;</p><p>  vector&lt;int&gt; v2;</p><p>  replace_copy(v.begin(), v.end(),</p><p>    back_inserter(v2), 8, 47);</p><p>  print(v2.begin(), v2.end(), "replace_copy 8 -&gt; 47", " ");</p><p>  replace_if(v.begin(), v.end(),</p><p>    bind2nd(greater_equal&lt;int&gt;(), 7), -1);</p><p>  print(v.begin(), v.end(), "replace_if &gt;= 7 -&gt; -1", " ");</p><p>} ///:~</p><empty-line/><p>The example begins with two predicates: <strong>PlusOne,</strong> which is a binary predicate that returns <strong>true</strong> if the second argument is equivalent to one plus the first argument; and <strong>MulMoreThan,</strong> which returns <strong>true</strong> if the first argument times the second argument is greater than a value stored in the object. These binary predicates are used as tests in the example. </p><p>In <strong>main( )</strong>, an array <strong>a</strong> is created and fed to the constructor for <strong>vector&lt;int&gt; v</strong>. This vector is used as the target for the search and replace activities, and you’ll note that there are duplicate elements—these are discovered by some of the search/replace routines<sup>.</sup></p><p>The first test demonstrates <strong>find( )</strong>, discovering the value 4 in <strong>v</strong>. The return value is the iterator pointing to the first instance of 4, or the end of the input range (<strong>v.end( )</strong>) if the search value is not found<sup>.</sup></p><p>The <strong>find_if( )</strong> algorithm uses a predicate to determine if it has discovered the correct element. In this example, this predicate is created on the fly using <strong>greater&lt;int&gt;</strong> (that is, "see if the first <strong>int </strong>argument is greater than the second") and <strong>bind2nd( )</strong> to fix the second argument to 8. Thus, it returns true if the value in <strong>v</strong> is greater than 8<sup>.</sup></p><p>Since two identical objects appear next to each other in a number of cases in <strong>v</strong>, the test of <strong>adjacent_find( )</strong> is designed to find them all. It starts looking from the beginning and then drops into a <strong>while</strong> loop, making sure that the iterator <strong>it</strong> has not reached the end of the input sequence (which would mean that no more matches can be found). For each match it finds, the loop prints the matches and then performs the next <strong>adjacent_find( )</strong>, this time using <strong>it + 1</strong> as the first argument (this way, it will still find two pairs in a triple).</p><p>You might look at the <strong>while</strong> loop and think that you can do it a bit more cleverly, to wit:<sup>.</sup></p><p>  while(it != v.end()) {</p><p>    cout &lt;&lt; "adjacent_find: " &lt;&lt; *it++</p><p>      &lt;&lt; ", " &lt;&lt; *it++ &lt;&lt; endl;</p><p>    it = adjacent_find(it, v.end());</p><p>  }</p><empty-line/><p>Of course, this is exactly what we tried first. However, we did not get the output we expected, on any compiler. This is because there is no guarantee about when the increments occur in this expression<sup>.</sup></p><p>The next test uses <strong>adjacent_find( )</strong> with the <strong>PlusOne</strong> predicate, which discovers all the places where the next number in the sequence <strong>v</strong> changes from the previous by one. The same <strong>while</strong> approach finds all the cases<sup>.</sup></p><p>The <strong>find_first_of( )</strong> algorithm requires a second range of objects for which to hunt; this is provided in the array <strong>b</strong>. Notice that, because the first range and the second range in <strong>find_first_of( )</strong> are controlled by separate template arguments, those ranges can refer to two different types of containers, as seen here. The second form of <strong>find_first_of( )</strong> is also tested, using <strong>PlusOne</strong><sup><strong>.</strong></sup></p><p>The <strong>search( )</strong> algorithm finds exactly the second range inside the first one, with the elements in the same order. The second form of <strong>search( )</strong> uses a predicate, which is typically just something that defines equivalence, but it also presents some interesting possibilities—here, the <strong>PlusOne</strong> predicate causes the range <strong>{ 4, 5, 6 }</strong> to be found<sup>.</sup></p><p>The <strong>find_end( )</strong> test discovers the <emphasis>last</emphasis> occurrence of the entire sequence <strong>{ 11, 11, 11 }</strong>. To show that it has in fact found the last occurrence, the rest of <strong>v</strong> starting from <strong>it</strong> is printed<sup>.</sup></p><p>The first <strong>search_n( )</strong> test looks for 3 copies of the value 7, which it finds and prints. When using the second version of <strong>search_n( )</strong>, the predicate is ordinarily meant to be used to determine equivalence between two elements, but we’ve taken some liberties and used a function object that multiplies the value in the sequence by (in this case) 15 and checks to see if it’s greater than 100. That is, the <strong>search_n( )</strong> test says "find me 6 consecutive values that, when multiplied by 15, each produce a number greater than 100." Not exactly what you normally expect to do, but it might give you some ideas the next time you have an odd searching problem<sup>.</sup></p><p>The <strong>min_element( )</strong> and <strong>max_element( )</strong> algorithms are straightforward; the only thing that’s a bit odd is that it looks like the function is being dereferenced with a ‘<strong>*</strong>’. Actually, the returned iterator is being dereferenced to produce the value for printing<sup>.</sup></p><p>To test replacements, <strong>replace_copy( )</strong> is used first (so it doesn’t modify the original vector) to replace all values of 8 with the value 47. Notice the use of <strong>back_inserter( )</strong> with the empty vector <strong>v2</strong>. To demonstrate <strong>replace_if( )</strong>, a function object is created using the standard template <strong>greater_equal</strong> along with <strong>bind2nd</strong> to replace all the values that are greater than or equal to 7 with the value -1<sup>.</sup></p></section></section></section><section><title><p>Comparing ranges</p></title><section><p>These algorithms provide ways to compare two ranges. At first glance, the operations they perform seem close to the <strong>search( )</strong> function. However, <strong>search( )</strong> tells you where the second sequence appears within the first, and <strong>equal( )</strong> and <strong>lexicographical_compare( ) </strong>simply tell you how two sequences compare. On the other hand, <strong>mismatch( )</strong> does tell you where the two sequences go out of sync, but those sequences must be exactly the same length<sup>.</sup></p><p>bool <strong>equal</strong>(InputIterator first1, InputIterator last1, InputIterator first2); bool <strong>equal</strong>(InputIterator first1, InputIterator last1, InputIterator first2 BinaryPredicate binary_pred);</p><p>In both these functions, the first range is the typical one, <strong>[first1, last1)</strong>. The second range starts at <strong>first2</strong>, but there is no "last2" because its length is determined by the length of the first range. The <strong>equal( )</strong> function returns true if both ranges are exactly the same (the same elements in the same order); in the first case, the <strong>operator==</strong> performs the comparison, and in the second case <strong>binary_pred</strong> decides if two elements are the same<sup>.</sup></p><p>bool <strong>lexicographical_compare</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2); bool <strong>lexicographical_compare</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, BinaryPredicate binary_pred);</p><p>These two functions determine if the first range is "lexicographically less" than the second. (They return <strong>true</strong> if range 1 is less than range 2, and false otherwise.) Lexicographical comparison, or "dictionary" comparison, means that the comparison is done the same way we establish the order of strings in a dictionary, one element at a time. The first elements determine the result if these elements are different, but if they’re equal, the algorithm moves on to the next elements and looks at those, and so on until it finds a mismatch. At that point, it looks at the elements, and if the element from range 1 is less than the element from range two, <strong>lexicographical_compare( )</strong> returns <strong>true</strong>; otherwise, it returns <strong>false</strong>. If it gets all the way through one range or the other (the ranges may be different lengths for this algorithm) without finding an inequality, range 1 is <emphasis>not </emphasis>less than range 2, so the function returns <strong>false</strong>.</p><p>If the two ranges are different lengths, a missing element in one range acts as one that "precedes" an element that exists in the other range, so "abc" precedes "abcd". If the algorithm reaches the end of one of the ranges without a mismatch, then the shorter range comes first. In that case, if the shorter range is the first range, the result is <strong>true</strong>, otherwise it is <strong>false</strong><sup><strong>.</strong></sup></p><p>In the first version of the function, <strong>operator&lt;</strong> performs the comparisons, and in the second version, <strong>binary_pred</strong> is used.</p><p>pair&lt;InputIterator1, InputIterator2&gt; <strong>mismatch</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2); pair&lt;InputIterator1, InputIterator2&gt; <strong>mismatch</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate binary_pred);</p><p>As in <strong>equal( )</strong>, the length of both ranges is exactly the same, so only the first iterator in the second range is necessary, and the length of the first range is used as the length of the second range. Whereas <strong>equal( )</strong> just tells you whether the two ranges are the same, <strong>mismatch( )</strong> tells you where they begin to differ. To accomplish this, you must be told (1) the element in the first range where the mismatch occurred and (2) the element in the second range where the mismatch occurred. These two iterators are packaged together into a <strong>pair</strong> object and returned. If no mismatch occurs, the return value is <strong>last1</strong> combined with the past-the-end iterator of the second range. The <strong>pair</strong> template class is a <strong>struct</strong> with two elements denoted by the member names <strong>first</strong> and <strong>second</strong> and is defined in the <strong>&lt;utility&gt;</strong> header<sup>.</sup></p><p>As in <strong>equal( )</strong>, the first function tests for equality using <strong>operator==</strong> while the second one uses <strong>binary_pred</strong>.</p></section><section><section><title><p>Example</p></title><p>Because the standard C++ <strong>string</strong> class is built like a container (it has <strong>begin( )</strong> and <strong>end( )</strong> member functions that produce objects of type <strong>string::iterator</strong>), it can be used to conveniently create ranges of characters to test with the STL comparison algorithms. However, note that <strong>string </strong>has a fairly complete set of native operations, so look at the <strong>string</strong> class before using the STL algorithms to perform operations.</p><p>//: C06:Comparison.cpp</p><p>// The STL range comparison algorithms</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "PrintSequence.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  // strings provide a convenient way to create</p><p>  // ranges of characters, but you should</p><p>  // normally look for native string operations:</p><p>  string s1("This is a test");</p><p>  string s2("This is a Test");</p><p>  cout &lt;&lt; "s1: " &lt;&lt; s1 &lt;&lt; endl</p><p>    &lt;&lt; "s2: " &lt;&lt; s2 &lt;&lt; endl;</p><p>  cout &lt;&lt; "compare s1 &amp; s1: "</p><p>    &lt;&lt; equal(s1.begin(), s1.end(), s1.begin())</p><p>    &lt;&lt; endl;</p><p>  cout &lt;&lt; "compare s1 &amp; s2: "</p><p>    &lt;&lt; equal(s1.begin(), s1.end(), s2.begin())</p><p>    &lt;&lt; endl;</p><p>  cout &lt;&lt; "lexicographical_compare s1 &amp; s1: " &lt;&lt;</p><p>    lexicographical_compare(s1.begin(), s1.end(),</p><p>      s1.begin(), s1.end()) &lt;&lt;  endl;</p><p>  cout &lt;&lt; "lexicographical_compare s1 &amp; s2: " &lt;&lt;</p><p>    lexicographical_compare(s1.begin(), s1.end(),</p><p>      s2.begin(), s2.end()) &lt;&lt; endl;</p><p>  cout &lt;&lt; "lexicographical_compare s2 &amp; s1: " &lt;&lt;</p><p>    lexicographical_compare(s2.begin(), s2.end(),</p><p>      s1.begin(), s1.end()) &lt;&lt; endl;</p><p>  cout &lt;&lt; "lexicographical_compare shortened "</p><p>    "s1 &amp; full-length s2: " &lt;&lt; endl;</p><p>  string s3(s1);</p><p>  while(s3.length() != 0) {</p><p>    bool result = lexicographical_compare(</p><p>      s3.begin(), s3.end(), s2.begin(),s2.end());</p><p>    cout &lt;&lt; s3 &lt;&lt; endl &lt;&lt; s2 &lt;&lt; ", result = "</p><p>      &lt;&lt; result &lt;&lt; endl;</p><p>    if(result == true) break;</p><p>    s3 = s3.substr(0, s3.length() - 1);</p><p>  }</p><p>  pair&lt;string::iterator, string::iterator&gt; p =</p><p>    mismatch(s1.begin(), s1.end(), s2.begin());</p><p>  print(p.first, s1.end(), "p.first", "");</p><p>  print(p.second, s2.end(), "p.second","");</p><p>} ///:~</p><empty-line/><p>Note that the only difference between <strong>s1</strong> and <strong>s2</strong> is the capital ‘T’ in <strong>s2</strong>’s "Test." Comparing <strong>s1</strong> and <strong>s1</strong> for equality yields <strong>true</strong>, as expected, while <strong>s1</strong> and <strong>s2</strong> are not equal because of the capital ‘T’.</p><p>To understand the output of the <strong>lexicographical_compare( )</strong> tests, remember two things: first, the comparison is performed character-by-character, and, second, on our platform, capital letters "precede" lowercase letters. In the first test, <strong>s1</strong> is compared to <strong>s1</strong>. These are exactly equivalent. One is <emphasis>not</emphasis> lexicographically less than the other (which is what the comparison is looking for), and thus the result is <strong>false</strong>. The second test is asking "does <strong>s1</strong> precede <strong>s2</strong>?" When the comparison gets to the ‘t’ in "test", it discovers that the lowercase ‘t’ in <strong>s1</strong> is "greater" than the uppercase ‘T’ in <strong>s2</strong>, so the answer is again <strong>false</strong>. However, if we test to see whether <strong>s2</strong> precedes <strong>s1</strong>, the answer is <strong>true</strong>.</p><p>To further examine lexicographical comparison, the next test in this example compares <strong>s1</strong> with <strong>s2</strong> again (which returned <strong>false</strong> before). But this time it repeats the comparison, trimming one character off the end of <strong>s1</strong> (which is first copied into <strong>s3</strong>) each time through the loop until the test evaluates to <strong>true</strong>. What you’ll see is that, as soon as the uppercase ‘T’ is trimmed off <strong>s3</strong> (the copy of <strong>s1</strong>), the characters, which are exactly equal up to that point, no longer count. Because <strong>s3</strong> is shorter than <strong>s2,</strong> it lexicographically precedes <strong>s2</strong>.</p><p>The final test uses <strong>mismatch( )</strong>. To capture the return value, create the appropriate <strong>pair p</strong>, constructing the template using the iterator type from the first range and the iterator type from the second range (in this case, both <strong>string::iterator</strong>s). To print the results, the iterator for the mismatch in the first range is <strong>p.first</strong>, and for the second range is <strong>p.second</strong>. In both cases, the range is printed from the mismatch iterator to the end of the range so you can see exactly where the iterator points.</p></section></section></section><section><title><p>Removing elements</p></title><section><p>Because of the genericity of the STL, the concept of removal is a bit constrained. Since elements can only be "removed" via iterators, and iterators can point to arrays, vectors, lists, and so on, it is not safe or reasonable to actually try to destroy the elements that are being removed and to change the size of the input range <strong>[first, last).</strong> (An array, for example, cannot have its size changed.) So instead, what the STL "remove" functions do is rearrange the sequence so that the "removed" elements are at the end of the sequence, and the "un-removed" elements are at the beginning of the sequence (in the same order that they were before, minus the removed elements—that is, this is a <emphasis>stable</emphasis> operation). Then the function will return an iterator to the "new last" element of the sequence, which is the end of the sequence without the removed elements and the beginning of the sequence of the removed elements. In other words, if <strong>new_last</strong> is the iterator that is returned from the "remove" function, <strong>[first, new_last)</strong> is the sequence without any of the removed elements, and <strong>[new_last, last)</strong> is the sequence of removed elements.</p><p>If you are simply using your sequence, including the removed elements, with more STL algorithms, you can just use <strong>new_last</strong> as the new past-the-end iterator. However, if you’re using a resizable container <strong>c </strong>(not an array) and you actually want to eliminate the removed elements from the container, you can use <strong>erase( )</strong> to do so, for example:<sup>.</sup></p><p>c.erase(remove(c.begin(), c.end(), value), c.end());</p><empty-line/><p>You can also use the <strong>resize( )</strong> member function that belongs to all standard sequences (more on this in the next chapter)<sup>.</sup></p><p>The return value of <strong>remove( )</strong> is the <strong>new_last</strong> iterator, so <strong>erase( )</strong> deletes all the removed elements from <strong>c</strong>.</p><p>The iterators in <strong>[new_last, last)</strong> are dereferenceable, but the element values are unspecified and should not be used.</p><p>ForwardIterator <strong>remove</strong>(ForwardIterator first, ForwardIterator last, const T&amp; value); ForwardIterator <strong>remove_if</strong>(ForwardIterator first, ForwardIterator last, Predicate pred); OutputIterator <strong>remove_copy</strong>(InputIterator first, InputIterator last, OutputIterator result, const T&amp; value); OutputIterator <strong>remove_copy_if</strong>(InputIterator first, InputIterator last, OutputIterator result, Predicate pred);</p><p>Each of the "remove" forms moves through the range <strong>[first, last)</strong>, finding values that match a removal criterion and copying the unremoved elements over the removed elements (thus effectively removing them). The original order of the unremoved elements is maintained. The return value is an iterator pointing past the end of the range that contains none of the removed elements. The values that this iterator points to are unspecified.</p><p>The "if" versions pass each element to <strong>pred( )</strong> to determine whether it should be removed. (If <strong>pred( )</strong> returns <strong>true</strong>, the element is removed.) The "copy" versions do not modify the original sequence, but instead copy the unremoved values into a range beginning at <strong>result</strong> and return an iterator indicating the past-the-end value of this new range.</p><p>ForwardIterator <strong>unique</strong>(ForwardIterator first, ForwardIterator last); ForwardIterator <strong>unique</strong>(ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred); OutputIterator <strong>unique_copy</strong>(InputIterator first, InputIterator last, OutputIterator result); OutputIterator <strong>unique_copy</strong>(InputIterator first, InputIterator last, OutputIterator result,  BinaryPredicate binary_pred);</p><p>Each of the "unique" functions moves through the range <strong>[first, last)</strong>, finding adjacent values that are equivalent (that is, duplicates) and "removing" the duplicate elements by copying over them. The original order of the unremoved elements is maintained. The return value is an iterator pointing past the end of the range that has the adjacent duplicates removed.</p><p>Because only duplicates that are adjacent are removed, it’s likely that you’ll want to call <strong>sort( )</strong> before calling a "unique" algorithm, since that will guarantee that <emphasis>all</emphasis> the duplicates are removed.</p><p>For each iterator value <strong>i</strong> in the input range, the versions containing <strong>binary_pred</strong> call:<sup>.</sup></p><p>binary_pred(*i, *(i-1));</p><empty-line/><p>and if the result is <strong>true</strong>, <strong>*i</strong> is considered a duplicate.</p><p>The "copy" versions do not modify the original sequence, but instead copy the unremoved values into a range beginning at <strong>result</strong> and return an iterator indicating the past-the-end value of this new range.</p></section><section><section><title><p>Example</p></title><p>This example gives a visual demonstration of the way the "remove" and "unique" functions work.</p><p>//: C06:Removing.cpp</p><p>// The removing algorithms</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cctype&gt;</p><p>#include &lt;string&gt;</p><p>#include "Generators.h"</p><p>#include "PrintSequence.h"</p><p>using namespace std;</p><empty-line/><p>struct IsUpper {</p><p>  bool operator()(char c) {</p><p>    return isupper(c);</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  string v;</p><p>  v.resize(25);</p><p>  generate(v.begin(), v.end(), CharGen());</p><p>  print(v.begin(), v.end(), "v original", "");</p><p>  // Create a set of the characters in v:</p><p>  string us(v.begin(), v.end());</p><p>  sort(us.begin(), us.end());</p><p>  string::iterator it = us.begin(), cit = v.end(),</p><p>    uend = unique(us.begin(), us.end());</p><p>  // Step through and remove everything:</p><p>  while(it != uend) {</p><p>    cit = remove(v.begin(), cit, *it);</p><p>    print(v.begin(), v.end(), "Complete v", "");</p><p>    print(v.begin(), cit, "Pseudo v ", " ");</p><p>    cout &lt;&lt; "Removed element:\t" &lt;&lt; *it</p><p>         &lt;&lt; "\nPsuedo Last Element:\t"</p><p>         &lt;&lt; *cit &lt;&lt; endl &lt;&lt; endl;</p><p>    it++;</p><p>  }</p><p>  generate(v.begin(), v.end(), CharGen());</p><p>  print(v.begin(), v.end(), "v", "");</p><p>  cit = remove_if(v.begin(), v.end(), IsUpper());</p><p>  print(v.begin(), cit, "v after remove_if IsUpper", " ");</p><p>  // Copying versions are not shown for remove</p><p>  // and remove_if.</p><p>  sort(v.begin(), cit);</p><p>  print(v.begin(), cit, "sorted", " ");</p><p>  string v2;</p><p>  v2.resize(cit - v.begin());</p><p>  unique_copy(v.begin(), cit, v2.begin());</p><p>  print(v2.begin(), v2.end(), "unique_copy", " ");</p><p>  // Same behavior:</p><p>  cit = unique(v.begin(), cit, equal_to&lt;char&gt;());</p><p>  print(v.begin(), cit, "unique equal_to&lt;char&gt;", " ");</p><p>} ///:~</p><empty-line/><p>The string <strong>v</strong>, which is a container of characters, as you know, is filled with randomly generated characters. Each character is used in a <strong>remove</strong> statement, but the entire string <strong>v</strong> is printed out each time so you can see what happens to the rest of the range, after the resulting endpoint (which is stored in <strong>cit</strong>).</p><p>To demonstrate <strong>remove_if( )</strong>, the address of the standard C library function <strong>isupper( ) </strong>(in <strong>&lt;cctype&gt; </strong>is called inside the function object class <strong>IsUpper</strong>, an object of which is passed as the predicate for <strong>remove_if( )</strong>. This returns <strong>true</strong> only if a character is uppercase, so only lowercase characters will remain. Here, the end of the range is used in the call to <strong>print( )</strong> so only the remaining elements will appear. The copying versions of <strong>remove( )</strong> and <strong>remove_if( )</strong> are not shown because they are a simple variation on the noncopying versions, which you should be able to use without an example.</p><p>The range of lowercase letters is sorted in preparation for testing the "unique" functions. (The "unique" functions are not undefined if the range isn’t sorted, but it’s probably not what you want.).. First, <strong>unique_copy( )</strong> puts the unique elements into a new <strong>vector</strong> using the default element comparison, and then the form of <strong>unique( )</strong> that takes a predicate is used; the predicate used is the built-in function object <strong>equal_to( )</strong>, which produces the same results as the default element comparison.</p></section></section></section><section><title><p>Sorting and operations on sorted ranges</p></title><section><p>A significant category of STL algorithms requires that the range they operate on be in sorted order.</p><p>STL provides a number of separate sorting algorithms, depending on whether the sort should be stable, partial, or just regular (non-stable). Oddly enough, only the partial sort has a copying version; otherwise you’ll need to make your own copy before sorting if that’s what you want<sup>.</sup></p><p>Once your sequence is sorted, you can perform many operations on that sequence, from simply locating an element or group of elements to merging with another sorted sequence or manipulating sequences as mathematical sets.</p><p>Each algorithm involved with sorting or operations on sorted sequences has two versions. The first uses the object’s own <strong>operator&lt;</strong> to perform the comparison, and the second uses <strong>operator( )(a, b)</strong> to determine the relative order of <strong>a</strong> and <strong>b</strong>. Other than this, there are no differences, so this distinction will not be pointed out in the description of each algorithm.</p></section><section><section><title><p>Sorting</p></title><p>The sort algorithms require ranges delimited by random-access iterators, such as a <strong>vector</strong> or <strong>deque</strong>. The <strong>list</strong> container has its own built-in <strong>sort( )</strong> function, since it only supports bi-directional iteration<sup>.</sup></p><p>void <strong>sort</strong>(RandomAccessIterator first, RandomAccessIterator last); void <strong>sort</strong>(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering binary_pred);</p><p>Sorts <strong>[first, last)</strong> into ascending order. The first form uses <strong>operator&lt;</strong> and the second form uses the supplied comparator object to determine the order.</p><p>void <strong>stable_sort</strong>(RandomAccessIterator first, RandomAccessIterator last); void <strong>stable_sort</strong>(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering binary_pred);</p><p>Sorts <strong>[first, last)</strong> into ascending order, preserving the original ordering of equivalent elements. (This is important if elements can be equivalent but not identical.)<sup>.</sup></p><p>void <strong>partial_sort</strong>(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last); void <strong>partial_sort</strong>(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last, StrictWeakOrdering binary_pred);</p><p>Sorts the number of elements from <strong>[first, last)</strong> that can be placed in the range <strong>[first, middle)</strong>. The rest of the elements end up in <strong>[middle, last)</strong> and have no guaranteed order<sup>.</sup></p><p>RandomAccessIterator <strong>partial_sort_copy</strong>(InputIterator first, InputIterator last, RandomAccessIterator result_first, RandomAccessIterator result_last); RandomAccessIterator <strong>partial_sort_copy</strong>(InputIterator first, InputIterator last, RandomAccessIterator result_first, RandomAccessIterator result_last, StrictWeakOrdering binary_pred);</p><p>Sorts the number of elements from <strong>[first, last)</strong> that can be placed in the range <strong>[result_first, result_last)</strong> and copies those elements into <strong>[result_first, result_last)</strong>. If the range <strong>[first, last)</strong> is smaller than <strong>[result_first, result_last)</strong>, the smaller number of elements is used<sup>.</sup></p><p>void <strong>nth_element</strong>(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last); void <strong>nth_element</strong>(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, StrictWeakOrdering binary_pred);</p><p>Just like <strong>partial_sort( )</strong>, <strong>nth_element( )</strong> partially orders a range of elements. However, it’s much "less ordered" than <strong>partial_sort( )</strong>. The only thing that <strong>nth_element( )</strong> guarantees is that whatever <emphasis>location </emphasis>you choose will become a dividing point. All the elements in the range <strong>[first, nth) </strong>will pair-wise satisfy the binary predicate (<strong>operator&lt;</strong> by default, as usual), and all the elements in the range <strong>(nth, last]</strong> will not. However, neither subrange is in any particular order, unlike <strong>partial_sort( )</strong> which has the first range in sorted order.</p><p>If all you need is this very weak ordering (if, for example, you’re determining medians, percentiles, and that sort of thing), this algorithm is faster than <strong>partial_sort( )</strong>.</p></section><section><title><p>Locating elements in sorted ranges</p></title><p>Once a range is sorted, you can use a group of operations to find elements within those ranges. In the following functions, there are always two forms. One assumes the intrinsic <strong>operator&lt;</strong> performs the sort, and the second operator must be used if some other comparison function object performs the sort. You must use the same comparison for locating elements as you do to perform the sort; otherwise, the results are undefined. In addition, if you try to use these functions on unsorted ranges, the results will be undefined.</p><p>bool <strong>binary_search</strong>(ForwardIterator first, ForwardIterator last, const T&amp; value); bool <strong>binary_search</strong>(ForwardIterator first, ForwardIterator last, const T&amp; value, StrictWeakOrdering binary_pred);</p><p>Tells you whether <strong>value</strong> appears in the sorted range <strong>[first, last)</strong>.</p><p>ForwardIterator <strong>lower_bound</strong>(ForwardIterator first, ForwardIterator last, const T&amp; value); ForwardIterator <strong>lower_bound</strong>(ForwardIterator first, ForwardIterator last, const T&amp; value, StrictWeakOrdering binary_pred);</p><p>Returns an iterator indicating the first occurrence of <strong>value</strong> in the sorted range <strong>[first, last)</strong>. If <strong>value</strong> is not present, an iterator to where it would fit in the sequence is returned<sup>.</sup></p><p>ForwardIterator <strong>upper_bound</strong>(ForwardIterator first, ForwardIterator last, const T&amp; value); ForwardIterator <strong>upper_bound</strong>(ForwardIterator first, ForwardIterator last, const T&amp; value, StrictWeakOrdering binary_pred);</p><p>Returns an iterator indicating one past the last occurrence of <strong>value</strong> in the sorted range <strong>[first, last)</strong>. If <strong>value</strong> is not present, an iterator to where it would fit in the sequence is returned.</p><p>pair&lt;ForwardIterator, ForwardIterator&gt; <strong>equal_range</strong>(ForwardIterator first, ForwardIterator last, const T&amp; value); pair&lt;ForwardIterator, ForwardIterator&gt; <strong>equal_range</strong>(ForwardIterator first, ForwardIterator last, const T&amp; value, StrictWeakOrdering binary_pred);</p><p>Essentially combines <strong>lower_bound( )</strong> and <strong>upper_bound( )</strong> to return a <strong>pair</strong> indicating the first and one-past-the-last occurrences of <strong>value</strong> in the sorted range <strong>[first, last)</strong>. Both iterators indicate the location where <strong>value</strong> would fit if it is not found.</p><p>You may find it surprising that the binary search algorithms take a forward iterator instead of a random access iterator. (Most explanations of binary search use indexing.) Remember that a random access iterator "is-a" forward iterator, and can be used wherever the latter is specified. If the iterator passed to one of these algorithms in fact supports random access, then the efficient logarithmic-time procedure is used, otherwise a linear search is performed.<sup>[88]</sup></p></section><section><title><p>Example</p></title><p>The following example turns each input word into an <strong>NString</strong> and added to a <strong>vector&lt;NString&gt;</strong>. The <strong>vector</strong> is then used to demonstrate the various sorting and searching algorithms<sup>.</sup></p><p>//: C06:SortedSearchTest.cpp</p><p>// Test searching in sorted ranges</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cassert&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;vector&gt;</p><p>#include "NString.h"</p><p>#include "PrintSequence.h"</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  typedef vector&lt;NString&gt;::iterator sit;</p><p>  char* fname = "test.txt";</p><p>  if(argc &gt; 1) fname = argv[1];</p><p>  ifstream in(fname);</p><p>  assure(in, fname);</p><p>  srand(time(0));</p><p>  cout.setf(ios::boolalpha);</p><p>  vector&lt;NString&gt; original;</p><p>  copy(istream_iterator&lt;string&gt;(in),</p><p>    istream_iterator&lt;string&gt;(), back_inserter(original));</p><p>  require(original.size() &gt;= 4, "Must have four elements");</p><p>  vector&lt;NString&gt; v(original.begin(), original.end()),</p><p>    w(original.size() / 2);</p><p>  sort(v.begin(), v.end());</p><p>  print(v.begin(), v.end(), "sort");</p><p>  v = original;</p><p>  stable_sort(v.begin(), v.end());</p><p>  print(v.begin(), v.end(), "stable_sort");</p><p>  v = original;</p><p>  sit it = v.begin(), it2;</p><p>  // Move iterator to middle</p><p>  for(size_t i = 0; i &lt; v.size() / 2; i++)</p><p>    it++;</p><p>  partial_sort(v.begin(), it, v.end());</p><p>  cout &lt;&lt; "middle = " &lt;&lt; *it &lt;&lt; endl;</p><p>  print(v.begin(), v.end(), "partial_sort");</p><p>  v = original;</p><p>  // Move iterator to a quarter position</p><p>  it = v.begin();</p><p>  for(size_t i = 0; i &lt; v.size() / 4; i++)</p><p>    it++;</p><p>  // Less elements to copy from than to the destination</p><p>  partial_sort_copy(v.begin(), it, w.begin(), w.end());</p><p>  print(w.begin(), w.end(), "partial_sort_copy");</p><p>  // Not enough room in destination</p><p>  partial_sort_copy(v.begin(), v.end(), w.begin(),</p><p>    w.end());</p><p>  print(w.begin(), w.end(), "w partial_sort_copy");</p><p>  // v remains the same through all this process</p><p>  assert(v == original);</p><p>  nth_element(v.begin(), it, v.end());</p><p>  cout &lt;&lt; "The nth_element = " &lt;&lt; *it &lt;&lt; endl;</p><p>  print(v.begin(), v.end(), "nth_element");</p><p>  string f = original[rand() % original.size()];</p><p>  cout &lt;&lt; "binary search: "</p><p>    &lt;&lt; binary_search(v.begin(), v.end(), f)</p><p>    &lt;&lt; endl;</p><p>  sort(v.begin(), v.end());</p><p>  it = lower_bound(v.begin(), v.end(), f);</p><p>  it2 = upper_bound(v.begin(), v.end(), f);</p><p>  print(it, it2, "found range");</p><p>  pair&lt;sit, sit&gt; ip =</p><p>    equal_range(v.begin(), v.end(), f);</p><p>  print(ip.first, ip.second,</p><p>    "equal_range");</p><p>} ///:~</p><empty-line/><p>This example uses the <strong>NString</strong> class seen earlier, which stores an occurrence number with copies of a string. The call to stable_sort( ) shows how the original order for objects with equal strings is preserved. You can also see what happens during a partial sort (the remaining unsorted elements are in no particular order). There is no "partial stable sort."<sup>.</sup></p><p>Notice in the call to <strong>nth_element( )</strong> that, whatever the nth element turns out to be (which will vary from one run to another because of <strong>URandGen</strong>), the elements before that are less, and after that are greater, but the elements have no particular order other than that. Because of <strong>URandGen</strong>, there are no duplicates, but if you use a generator that allows duplicates, you’ll see that the elements before the nth element will be less than or equal to the nth element.</p><p>This example also illustrates all three binary search algorithms. As advertised, <strong>lower_bound( )</strong> refers to the first element in the sequence equal to a given key, <strong>upper_bound( )</strong> points one past the last, and <strong>equal_range( )</strong> returns both results as a pair<sup>.</sup></p></section><section><title><p>Merging sorted ranges</p></title><p>As before, the first form of each function assumes the intrinsic <strong>operator&lt;</strong> performs the sort. The second form must be used if some other comparison function object performs the sort. You must use the same comparison for locating elements as you do to perform the sort; otherwise, the results are undefined. In addition, if you try to use these functions on unsorted ranges, the results will be undefined.</p><p>OutputIterator <strong>merge</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); OutputIterator <strong>merge</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering binary_pred);</p><p>Copies elements from <strong>[first1, last1)</strong> and <strong>[first2, last2)</strong> into <strong>result</strong>, such that the resulting range is sorted in ascending order. This is a stable operation.</p><p>void <strong>inplace_merge</strong>(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last); void <strong>inplace_merge</strong>(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, StrictWeakOrdering binary_pred);</p><p>This assumes that <strong>[first, middle)</strong> and <strong>[middle, last)</strong> are each sorted ranges in the same sequence. The two ranges are merged so that the resulting range <strong>[first, last)</strong> contains the combined ranges in sorted order<sup>.</sup></p></section><section><title><p>Example</p></title><p>It’s easier to see what goes on with merging if <strong>int</strong>s are used; the following example also emphasizes how the algorithms (and our own <strong>print</strong> template) work with arrays as well as containers<sup>.</sup></p><p>//: C06:MergeTest.cpp</p><p>// Test merging in sorted ranges</p><p>#include &lt;algorithm&gt;</p><p>#include "PrintSequence.h"</p><p>#include "Generators.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  const int sz = 15;</p><p>  int a[sz*2] = {0};</p><p>  // Both ranges go in the same array:</p><p>  generate(a, a + sz, SkipGen(0, 2));</p><p>  a[3] = 4;</p><p>  a[4] = 4;</p><p>  generate(a + sz, a + sz*2, SkipGen(1, 3));</p><p>  print(a, a + sz, "range1", " ");</p><p>  print(a + sz, a + sz*2, "range2", " ");</p><p>  int b[sz*2] = {0}; // Initialize all to zero</p><p>  merge(a, a + sz, a + sz, a + sz*2, b);</p><p>  print(b, b + sz*2, "merge", " ");</p><p>  // Reset b</p><p>  for(int i = 0; i &lt; sz*2; i++)</p><p>    b[i] = 0;</p><p>  inplace_merge(a, a + sz, a + sz*2);</p><p>  print(a, a + sz*2, "inplace_merge", " ");</p><p>  int* end = set_union(a, a + sz, a + sz, a + sz*2, b);</p><p>  print(b, end, "set_union", " ");</p><p>} ///:~</p><empty-line/><p>In <strong>main( )</strong>, instead of creating two separate arrays, both ranges are created end to end in the same array <strong>a.</strong> (This will come in handy for the <strong>inplace_merge.</strong>) The first call to <strong>merge( )</strong> places the result in a different array, <strong>b</strong>. For comparison, <strong>set_union( )</strong> is also called, which has the same signature and similar behavior, except that it removes duplicates from the second set. Finally, <strong>inplace_merge( )</strong> combines both parts of <strong>a</strong><sup><strong>.</strong></sup></p></section><section><title><p>Set operations on sorted ranges</p></title><p>Once ranges have been sorted, you can perform mathematical set operations on them.</p><p>bool <strong>includes</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2); bool <strong>includes</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, StrictWeakOrdering binary_pred);</p><p>Returns <strong>true</strong> if <strong>[first2, last2)</strong> is a subset of <strong>[first1, last1)</strong>. Neither range is required to hold only unique elements, but if <strong>[first2, last2)</strong> holds <strong>n</strong> elements of a particular value, <strong>[first1, last1)</strong> must also hold at least <strong>n</strong> elements if the result is to be <strong>true</strong>.</p><p>OutputIterator <strong>set_union</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); OutputIterator <strong>set_union</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering binary_pred);</p><p>Creates the mathematical union of two sorted ranges in the <strong>result</strong> range, returning the end of the output range. Neither input range is required to hold only unique elements, but if a particular value appears multiple times in both input sets, the resulting set will contain the larger number of identical values.</p><p>OutputIterator <strong>set_intersection</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); OutputIterator <strong>set_intersection</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering binary_pred);</p><p>Produces, in <strong>result</strong>, the intersection of the two input sets, returning the end of the output range—that is, the set of values that appear in both input sets. Neither input range is required to hold only unique elements, but if a particular value appears multiple times in both input sets, the resulting set will contain the smaller number of identical values.</p><p>OutputIterator <strong>set_difference</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); OutputIterator <strong>set_difference</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering binary_pred);</p><p>Produces, in <strong>result</strong>, the mathematical set difference, returning the end of the output range. All the elements that are in <strong>[first1, last1)</strong> but not in <strong>[first2, last2)</strong> are placed in the result set. Neither input range is required to hold only unique elements, but if a particular value appears multiple times in both input sets (<strong>n</strong> times in set 1 and <strong>m</strong> times in set 2), the resulting set will contain <strong>max(n-m, 0)</strong> copies of that value.</p><p>OutputIterator <strong>set_symmetric_difference</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); OutputIterator <strong>set_symmetric_difference</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering binary_pred);</p><p>Constructs, in <strong>result</strong>, the set containing:<sup>.</sup></p><p>1.All the elements in set 1 that are not in set 2</p><p>2.All the elements in set 2 that are not in set 1.</p><p>Neither input range is required to hold only unique elements, but if a particular value appears multiple times in both input sets (<strong>n</strong> times in set 1 and <strong>m</strong> times in set 2), the resulting set will contain <strong>abs(n-m)</strong> copies of that value, in which <strong>abs( )</strong> is the absolute value. The return value is the end of the output range.</p></section><section><title><p>Example</p></title><p>It’s easiest to see the set operations demonstrated using simple vectors of characters, so you view the sets more easily. These characters are randomly generated and then sorted, but the duplicates are not removed so you can see what the set operations do when duplicates are involved.</p><p>//: C06:SetOperations.cpp</p><p>// Set operations on sorted ranges</p><p>#include &lt;vector&gt;</p><p>#include &lt;algorithm&gt;</p><p>#include "PrintSequence.h"</p><p>#include "Generators.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  const int sz = 30;</p><p>  char v[sz + 1], v2[sz + 1];</p><p>  CharGen g;</p><p>  generate(v, v + sz, g);</p><p>  generate(v2, v2 + sz, g);</p><p>  sort(v, v + sz);</p><p>  sort(v2, v2 + sz);</p><p>  print(v, v + sz, "v", "");</p><p>  print(v2, v2 + sz, "v2", "");</p><p>  bool b = includes(v, v + sz, v + sz/2, v + sz);</p><p>  cout.setf(ios::boolalpha);</p><p>  cout &lt;&lt; "includes: " &lt;&lt; b &lt;&lt; endl;</p><p>  char v3[sz*2 + 1], *end;</p><p>  end = set_union(v, v + sz, v2, v2 + sz, v3);</p><p>  print(v3, end, "set_union", "");</p><p>  end = set_intersection(v, v + sz,</p><p>    v2, v2 + sz, v3);</p><p>  print(v3, end, "set_intersection", "");</p><p>  end = set_difference(v, v + sz, v2, v2 + sz, v3);</p><p>  print(v3, end, "set_difference", "");</p><p>  end = set_symmetric_difference(v, v + sz,</p><p>    v2, v2 + sz, v3);</p><p>  print(v3, end, "set_symmetric_difference","");</p><p>} ///:~</p><empty-line/><p>After <strong>v</strong> and <strong>v2</strong> are generated, sorted, and printed, the <strong>includes( )</strong> algorithm is tested by seeing if the entire range of <strong>v</strong> contains the last half of <strong>v</strong>, which of course it does; so the result should always be true. The array <strong>v3</strong> holds the output of <strong>set_union( )</strong>, <strong>set_intersection( )</strong>, <strong>set_difference( ),</strong> and <strong>set_symmetric_difference( )</strong>, and the results of each are displayed so you can ponder them and convince yourself that the algorithms do indeed work as promised<sup>.</sup></p></section></section></section><section><title><p>Heap operations</p></title><p>A heap is an array-like data structure used to implement a "priority queue", which is just a range that is organized in a way that accommodates retrieving elements by priority according to some comparison function. The heap operations in the standard library allow a sequence to be treated as a "heap" data structure, which always efficiently returns the element of highest priority, without fully ordering the entire sequence<sup>.</sup></p><p>As with the "sort" operations, there are two versions of each function. The first uses the object’s own <strong>operator&lt;</strong> to perform the comparison; the second uses an additional <strong>StrictWeakOrdering</strong> object’s <strong>operator( )(a, b)</strong> to compare two objects for <strong>a &lt; b</strong><sup><strong>.</strong></sup></p><p>void <strong>make_heap</strong>(RandomAccessIterator first, RandomAccessIterator last); void <strong>make_heap</strong>(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering binary_pred);</p><p>Turns an arbitrary range into a heap<sup>.</sup></p><p>void <strong>push_heap</strong>(RandomAccessIterator first, RandomAccessIterator last); void <strong>push_heap</strong>(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering binary_pred);</p><p>Adds the element *(<strong>last-1)</strong> to the heap determined by the range <strong>[first, last-1)</strong>. In other words, it places the last element in its proper location in the heap.</p><p>void <strong>pop_heap</strong>(RandomAccessIterator first, RandomAccessIterator last); void <strong>pop_heap</strong>(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering binary_pred);</p><p>Places the largest element (which is actually in <strong>*first</strong>, before the operation, because of the way heaps are defined) into the position <strong>*(last-1)</strong><emphasis>and</emphasis> reorganizes the remaining range so that it’s still in heap order. If you simply grabbed <strong>*first</strong>, the next element would not be the next-largest element; so you must use <strong>pop_heap( )</strong> if you want to maintain the heap in its proper priority-queue order.</p><p>void <strong>sort_heap</strong>(RandomAccessIterator first, RandomAccessIterator last); void <strong>sort_heap</strong>(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering binary_pred);</p><p>This could be thought of as the complement of <strong>make_heap( )</strong>. It takes a range that is in heap order and turns it into ordinary sorted order, so it is no longer a heap. That means that if you call <strong>sort_heap( ),</strong> you can no longer use <strong>push_heap( )</strong> or <strong>pop_heap( )</strong> on that range. (Rather, you can use those functions, but they won’t do anything sensible.) This is not a stable sort.</p></section><section><title><p>Applying an operation to each element in a range</p></title><section><p>These algorithms move through the entire range and perform an operation on each element. They differ in what they do with the results of that operation: <strong>for_each( )</strong> discards the return value of the operation, and <strong>transform( )</strong> places the results of each operation into a destination sequence (which can be the original sequence).</p><p>UnaryFunction <strong>for_each</strong>(InputIterator first, InputIterator last, UnaryFunction f);<sup>.</sup></p><p>Applies the function object <strong>f</strong> to each element in <strong>[first, last)</strong>, discarding the return value from each individual application of <strong>f</strong>. If <strong>f </strong>is just a function pointer, you are typically not interested in the return value; but if <strong>f </strong>is an object that maintains some internal state, it can capture the combined return value of being applied to the range. The final return value of <strong>for_each( )</strong> is <strong>f</strong>.</p><p>OutputIterator <strong>transform</strong>(InputIterator first, InputIterator last, OutputIterator result, UnaryFunction f); OutputIterator <strong>transform</strong>(InputIterator1 first, InputIterator1 last, InputIterator2 first2, OutputIterator result, BinaryFunction f);</p><p>Like <strong>for_each( )</strong>, <strong>transform( )</strong> applies a function object <strong>f</strong> to each element in the range <strong>[first, last)</strong>. However, instead of discarding the result of each function call, <strong>transform( )</strong> copies the result (using <strong>operator=</strong>) into <strong>*result</strong>, incrementing <strong>result</strong> after each copy. (The sequence pointed to by <strong>result</strong> must have enough storage; otherwise, use an inserter to force insertions instead of assignments.)</p><p>The first form of <strong>transform( )</strong> simply calls <strong>f(*first)</strong>, where first ranges through the input sequence. Similarly, the second form calls <strong>f(*first1, *first2)</strong>. (Note that the length of the second input range is determined by the length of the first.) The return value in both cases is the past-the-end iterator for the resulting output range.</p></section><section><section><title><p>Examples</p></title><p>Since much of what you do with objects in a container is to apply an operation to all those objects, these are fairly important algorithms and merit several illustrations.</p><p>First, consider <strong>for_each( )</strong>. This sweeps through the range, pulling out each element and passing it as an argument as it calls whatever function object it’s been given. Thus, <strong>for_each( )</strong> performs operations that you might normally write out by hand. If you look in your compiler’s header file at the template defining <strong>for_each( )</strong>, you’ll see something like this:<sup>.</sup></p><p>template &lt;class InputIterator, class Function&gt;</p><p>Function for_each(InputIterator first,</p><p>   InputIterator last,</p><p>   Function f) {</p><p>    while (first != last) f(*first++);</p><p>    return f;</p><p>}</p><p>The following example shows several ways this template can be expanded. First, we need a class that keeps track of its objects so we can know that it’s being properly destroyed:<sup>.</sup></p><p>//: C06:Counted.h</p><p>// An object that keeps track of itself</p><p>#ifndef COUNTED_H</p><p>#define COUNTED_H</p><p>#include &lt;vector&gt;</p><p>#include &lt;iostream&gt;</p><empty-line/><p>class Counted {</p><p>  static int count;</p><p>  char* ident;</p><p>public:</p><p>  Counted(char* id) : ident(id) { count++; }</p><empty-line/><p>  ~Counted() {</p><p>    std::cout &lt;&lt; ident &lt;&lt; " count = "</p><p>      &lt;&lt; --count &lt;&lt; std::endl;</p><p>  }</p><p>};</p><empty-line/><p>int Counted::count = 0;</p><empty-line/><p>class CountedVector :</p><p>  public std::vector&lt;Counted*&gt; {</p><p>public:</p><p>  CountedVector(char* id) {</p><p>    for(int i = 0; i &lt; 5; i++)</p><p>      push_back(new Counted(id));</p><p>  }</p><p>};</p><p>#endif // COUNTED_H ///:~</p><empty-line/><p>The <strong>class Counted</strong> keeps a static count of how many <strong>Counted</strong> objects have been created and tells you as they are destroyed.<sup>[89]</sup> In addition, each <strong>Counted</strong> keeps a <strong>char*</strong> identifier to make tracking the output easier.</p><p>The <strong>CountedVector</strong> is derived from <strong>vector&lt;Counted*&gt;</strong>, and in the constructor it creates some <strong>Counted</strong> objects, handing each one your desired <strong>char*</strong>. The <strong>CountedVector</strong> makes testing quite simple, as you’ll see<sup>.</sup></p><p>//: C06:ForEach.cpp</p><p>// Use of STL for_each() algorithm</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "Counted.h"</p><p>using namespace std;</p><empty-line/><p>// Function object:</p><p>template&lt;class T&gt;</p><p>class DeleteT {</p><p>public:</p><p>  void operator()(T* x) { delete x; }</p><p>};</p><empty-line/><p>// Template function:</p><p>template &lt;class T&gt;</p><p>void wipe(T* x) { delete x; }</p><empty-line/><p>int main() {</p><p>  CountedVector B("two");</p><p>  for_each(B.begin(),B.end(),DeleteT&lt;Counted&gt;());</p><p>  CountedVector C("three");</p><p>  for_each(C.begin(), C.end(), wipe&lt;Counted&gt;);</p><p>} ///:~</p><empty-line/><p>Since this is obviously something you might want to do a lot, why not create an algorithm to <strong>delete</strong> all the pointers in a container? You could use <strong>transform( )</strong>. The value of <strong>transform( )</strong> over <strong>for_each( )</strong> is that <strong>transform( )</strong> assigns the result of calling the function object into a resulting range, which can actually be the input range. That case means a literal transformation for the input range, since each element would be a modification of its previous value. In this example, this approach would be especially useful since it’s more appropriate to assign to each pointer the safe value of zero after calling <strong>delete</strong> for that pointer. <strong>Transform( )</strong> can easily do this:<sup>.</sup></p><p>//: C06:Transform.cpp</p><p>// Use of STL transform() algorithm</p><p>#include "Counted.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;vector&gt;</p><p>#include &lt;algorithm&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T&gt;</p><p>T* deleteP(T* x) { delete x; return 0; }</p><empty-line/><p>#ifdef _MSC_VER</p><p>// Microsoft needs explicit instantiation</p><p>template Counted* deleteP(Counted* x);</p><p>#endif</p><empty-line/><empty-line/><p>template&lt;class T&gt; struct Deleter {</p><p>  T* operator()(T* x) { delete x; return 0; }</p><p>};</p><empty-line/><p>int main() {</p><p>  CountedVector cv("one");</p><p>  transform(cv.begin(), cv.end(), cv.begin(),</p><p>    deleteP&lt;Counted&gt;);</p><p>  CountedVector cv2("two");</p><p>  transform(cv2.begin(), cv2.end(), cv2.begin(),</p><p>    Deleter&lt;Counted&gt;());</p><p>} ///:~</p><empty-line/><p>This shows both approaches: using a template function or a templatized function object. After the call to <strong>transform( )</strong>, the vector contains five null pointers, which is safer since any duplicate <strong>delete</strong>s will have no effect.</p><p>One thing you cannot do is <strong>delete</strong> every pointer in a collection without wrapping the call to <strong>delete </strong>inside a function or an object. That is, you do the following:<sup>.</sup></p><p>for_each(a.begin(), a.end(), ptr_fun(operator delete));</p><empty-line/><p>This has the same problem as the call to <strong>destroy ( )</strong> did earlier: <strong>operator delete( )</strong> takes a void*, but iterators aren’t void pointers (or pointers at all). Even if you could make it compile, what you’d get is a sequence of calls to the function that releases the storage. You will not get the effect of calling <strong>delete</strong> for each pointer in <strong>a</strong>, however; the destructor will not be called. This is typically not what you want, so you will need wrap your calls to <strong>delete</strong><sup><strong>.</strong></sup></p><p>In the previous example of <strong>for_each( )</strong>, the return value of the algorithm was ignored. This return value is the function that is passed in to <strong>for_each( )</strong>. If the function is just a pointer to a function, the return value is not very useful, but if it is a function object, that function object may have internal member data that it uses to accumulate information about all the objects that it sees during <strong>for_each( )</strong>.</p><p>For example, consider a simple model of inventory. Each <strong>Inventory</strong> object has the type of product it represents (here, single characters will be used for product names), the quantity of that product, and the price of each item:<sup>.</sup></p><p>//: C06:Inventory.h</p><p>#ifndef INVENTORY_H</p><p>#define INVENTORY_H</p><p>#include &lt;iostream&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><empty-line/><p>#ifndef _MSC_VER</p><p>// Microsoft namespace work-around</p><p>using std::rand;</p><p>using std::srand;</p><p>using std::time;</p><p>#endif</p><empty-line/><p>class Inventory {</p><p>  char item;</p><p>  int quantity;</p><p>  int value;</p><p>public:</p><p>  Inventory(char it, int quant, int val)</p><p>    : item(it), quantity(quant), value(val) {}</p><p>  // Synthesized operator= &amp; copy-constructor OK</p><p>  char getItem() const { return item; }</p><p>  int getQuantity() const { return quantity; }</p><p>  void setQuantity(int q) { quantity = q; }</p><p>  int getValue() const { return value; }</p><p>  void setValue(int val) { value = val; }</p><p>  friend std::ostream&amp; operator&lt;&lt;(</p><p>    std::ostream&amp; os, const Inventory&amp; inv) {</p><p>    return os &lt;&lt; inv.item &lt;&lt; ": "</p><p>      &lt;&lt; "quantity " &lt;&lt; inv.quantity</p><p>      &lt;&lt; ", value " &lt;&lt; inv.value;</p><p>  }</p><p>};</p><empty-line/><p>// A generator:</p><p>struct InvenGen {</p><p>  InvenGen() { srand(time(0)); }</p><p>  Inventory operator()() {</p><p>    static char c = 'a';</p><p>    int q = rand() % 100;</p><p>    int v = rand() % 500;</p><p>    return Inventory(c++, q, v);</p><p>  }</p><p>};</p><p>#endif // INVENTORY_H ///:~</p><empty-line/><p>Member functions get the item name and get and set quantity and value. An <strong>operator&lt;&lt;</strong> prints the <strong>Inventory</strong> object to an <strong>ostream</strong>. A generator creates objects that have sequentially labeled items and random quantities and values<sup>.</sup></p><p>To find out the total number of items and total value, you can create a function object to use with <strong>for_each( )</strong> that has data members to hold the totals:<sup>.</sup></p><p>//: C06:CalcInventory.cpp</p><p>// More use of for_each()</p><p>#include "Inventory.h"</p><p>#include "PrintSequence.h"</p><p>#include &lt;vector&gt;</p><p>#include &lt;algorithm&gt;</p><p>using namespace std;</p><empty-line/><p>// To calculate inventory totals:</p><p>class InvAccum {</p><p>  int quantity;</p><p>  int value;</p><p>public:</p><p>  InvAccum() : quantity(0), value(0) {}</p><p>  void operator()(const Inventory&amp; inv) {</p><p>    quantity += inv.getQuantity();</p><p>    value += inv.getQuantity() * inv.getValue();</p><p>  }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const InvAccum&amp; ia) {</p><p>    return os &lt;&lt; "total quantity: "</p><p>      &lt;&lt; ia.quantity</p><p>      &lt;&lt; ", total value: " &lt;&lt; ia.value;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  vector&lt;Inventory&gt; vi;</p><p>  generate_n(back_inserter(vi), 15, InvenGen());</p><p>  print(vi.begin(), vi.end(), "vi");</p><p>  InvAccum ia = for_each(vi.begin(),vi.end(),</p><p>    InvAccum());</p><p>  cout &lt;&lt; ia &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p><strong>InvAccum</strong>’s <strong>operator( )</strong> takes a single argument, as required by <strong>for_each( )</strong>. As <strong>for_each( )</strong> moves through its range, it takes each object in that range and passes it to <strong>InvAccum::operator( )</strong>, which performs calculations and saves the result. At the end of this process, <strong>for_each( )</strong> returns the <strong>InvAccum</strong> object that you can then examine; in this case, it is simply printed.</p><p>You can do most things to the <strong>Inventory</strong> objects using <strong>for_each( )</strong>. For example, <strong>for_each( )</strong> can handily increase all the prices by 10%. But you’ll notice that the <strong>Inventory</strong> objects have no way to change the <strong>item</strong> value. The programmers who designed <strong>Inventory</strong> thought this was a good idea. After all, why would you want to change the name of an item? But marketing has decided that they want a "new, improved" look by changing all the item names to uppercase; they’ve done studies and determined that the new names will boost sales (well, marketing has to have <emphasis>something</emphasis> to do …). So <strong>for_each( )</strong> will not work here, but <strong>transform( )</strong> will:</p><p>//: C06:TransformNames.cpp</p><p>// More use of transform()</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cctype&gt;</p><p>#include &lt;vector&gt;</p><p>#include "Inventory.h"</p><p>#include "PrintSequence.h"</p><p>using namespace std;</p><empty-line/><p>struct NewImproved {</p><p>  Inventory operator()(const Inventory&amp; inv) {</p><p>    return Inventory(toupper(inv.getItem()),</p><p>      inv.getQuantity(), inv.getValue());</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  vector&lt;Inventory&gt; vi;</p><p>  generate_n(back_inserter(vi), 15, InvenGen());</p><p>  print(vi.begin(), vi.end(), "vi");</p><p>  transform(vi.begin(), vi.end(), vi.begin(),</p><p>    NewImproved());</p><p>  print(vi.begin(), vi.end(), "vi");</p><p>} ///:~</p><empty-line/><p>Notice that the resulting range is the same as the input range; that is, the transformation is performed in place.</p><p>Now suppose that the sales department needs to generate special price lists with different discounts for each item. The original list must stay the same, and any number of special lists need to be generated. Sales will give you a separate list of discounts for each new list. To solve this problem, we can use the second version of <strong>transform( )</strong>:</p><p>//: C06:SpecialList.cpp</p><p>// Using the second version of transform()</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;vector&gt;</p><p>#include "Inventory.h"</p><p>#include "PrintSequence.h"</p><p>using namespace std;</p><empty-line/><p>struct Discounter {</p><p>  Inventory operator()(const Inventory&amp; inv,</p><p>    float discount) {</p><p>    return Inventory(inv.getItem(),</p><p>      inv.getQuantity(),</p><p>      int(inv.getValue() * (1 - discount)));</p><p>  }</p><p>};</p><empty-line/><p>struct DiscGen {</p><p>  DiscGen() { srand(time(0)); }</p><p>  float operator()() {</p><p>    float r = float(rand() % 10);</p><p>    return r / 100.0;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  vector&lt;Inventory&gt; vi;</p><p>  generate_n(back_inserter(vi), 15, InvenGen());</p><p>  print(vi.begin(), vi.end(), "vi");</p><p>  vector&lt;float&gt; disc;</p><p>  generate_n(back_inserter(disc), 15, DiscGen());</p><p>  print(disc.begin(), disc.end(), "Discounts:");</p><p>  vector&lt;Inventory&gt; discounted;</p><p>  transform(vi.begin(),vi.end(), disc.begin(),</p><p>    back_inserter(discounted), Discounter());</p><p>  print(discounted.begin(), discounted.end(),</p><p>        "discounted");</p><p>} ///:~</p><empty-line/><p>Given an <strong>Inventory</strong> object and a discount percentage, the Discounter function object produces a new <strong>Inventory</strong> with the discounted price. The <strong>DiscGen</strong> function object just generates random discount values between 1% and 10% to use for testing. In <strong>main( )</strong>, two <strong>vector</strong>s are created, one for <strong>Inventory</strong> and one for discounts. These are passed to <strong>transform( )</strong> along with a <strong>Discounter</strong> object, and <strong>transform( ) </strong>fills a new <strong>vector&lt;Inventory&gt;</strong> called <strong>discounted</strong>.</p></section></section></section><section><title><p>Numeric algorithms</p></title><section><p>These algorithms are all tucked into the header <strong>&lt;numeric&gt;</strong>, since they are primarily useful for performing numeric calculations.</p><p>&lt;numeric&gt; T <strong>accumulate</strong>(InputIterator first, InputIterator last, T result); T <strong>accumulate</strong>(InputIterator first, InputIterator last, T result, BinaryFunction f);</p><p>The first form is a generalized summation; for each element pointed to by an iterator <strong>i</strong> in <strong>[first, last)</strong>, it performs the operation <strong>result = result + *i</strong>, in which <strong>result</strong> is of type <strong>T</strong>. However, the second form is more general; it applies the function <strong>f(result, *i)</strong> on each element <strong>*i</strong> in the range from beginning to end<sup>.</sup></p><p>Note the similarity between the second form of <strong>transform( )</strong> and the second form of <strong>accumulate( )</strong><sup><strong>.</strong></sup></p><p>&lt;numeric&gt; T <strong>inner_product</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init); T <strong>inner_product</strong>(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, BinaryFunction1 op1, BinaryFunction2 op2);</p><p>Calculates a generalized inner product of the two ranges <strong>[first1, last1)</strong> and <strong>[first2, first2 + (last1 - first1))</strong>. The return value is produced by multiplying the element from the first sequence by the "parallel" element in the second sequence and then adding it to the sum. Thus, if you have two sequences {1, 1, 2, 2} and {1, 2, 3, 4}, the inner product becomes<sup>.</sup></p><p>(1*1) + (1*2) + (2*3) + (2*4)</p><empty-line/><p>which is 17. The <strong>init</strong> argument is the initial value for the inner product; this is probably zero but may be anything and is especially important for an empty first sequence, because then it becomes the default return value. The second sequence must have at least as many elements as the first.</p><p>The second form simply applies a pair of functions to its sequence. The <strong>op1</strong> function is used in place of addition, and <strong>op2</strong> is used instead of multiplication. Thus, if you applied the second version of <strong>inner_product( )</strong> to the sequence, the result would be the following operations:</p><p>init = op1(init, op2(1,1));</p><p>init = op1(init, op2(1,2));</p><p>init = op1(init, op2(2,3));</p><p>init = op1(init, op2(2,4));</p><empty-line/><p>Thus, it’s similar to <strong>transform( ),</strong> but two operations are performed instead of one.</p><p>&lt;numeric&gt; OutputIterator <strong>partial_sum</strong>(InputIterator first, InputIterator last, OutputIterator result); OutputIterator <strong>partial_sum</strong>(InputIterator first, InputIterator last, OutputIterator result, BinaryFunction op);</p><p>Calculates a generalized partial sum. This means that a new sequence is created, beginning at <strong>result</strong>; each element is the sum of all the elements up to the currently selected element in <strong>[first, last)</strong>. For example, if the original sequence is <strong>{1, 1, 2, 2, 3},</strong> the generated sequence is <strong>{1, 1 + 1, 1 + 1 + 2, 1 + 1 + 2 + 2, 1 + 1 + 2 + 2 + 3}</strong>, that is, <strong>{1, 2, 4, 6, 9}</strong>.</p><p>In the second version, the binary function <strong>op</strong> is used instead of the <strong>+</strong> operator to take all the "summation" up to that point and combine it with the new value. For example, if you use <strong>multiplies&lt;int&gt;( )</strong> as the object for the sequence, the output is <strong>{1, 1, 2, 4, 12}</strong>. Note that the first output value is always the same as the first input value.</p><p>The return value is the end of the output range <strong>[result, result + (last - first) )</strong>.</p><p>&lt;numeric&gt; OutputIterator <strong>adjacent_difference</strong>(InputIterator first, InputIterator last, OutputIterator result); OutputIterator <strong>adjacent_difference</strong>(InputIterator first, InputIterator last, OutputIterator result, BinaryFunction op);</p><p>Calculates the differences of adjacent elements throughout the range <strong>[first, last)</strong>. This means that in the new sequence, the value is the value of the difference of the current element and the previous element in the original sequence (the first value is unchanged). For example, if the original sequence is <strong>{1, 1, 2, 2, 3}</strong>, the resulting sequence is <strong>{1, 1 – 1, 2 – 1, 2 – 2, 3 – 2}</strong>, that is: <strong>{1, 0, 1, 0, 1}</strong>.</p><p>The second form uses the binary function <strong>op</strong> instead of the – operator to perform the "differencing." For example, if you use <strong>multiplies&lt;int&gt;( )</strong> as the function object for the sequence, the output is <strong>{1, 1, 2, 4, 6}</strong>.</p><p>The return value is the end of the output range <strong>[result, result + (last - first) )</strong>.</p></section><section><section><title><p>Example</p></title><p>This program tests all the algorithms in <strong>&lt;numeric&gt;</strong> in both forms, on integer arrays. You’ll notice that in the test of the form where you supply the function or functions, the function objects used are the ones that produce the same result as form one, so the results will be exactly the same. This should also demonstrate a bit more clearly the operations that are going on and how to substitute your own operations.</p><p>//: C06:NumericTest.cpp</p><p>//{L} ../TestSuite/Test</p><p>#include "PrintSequence.h"</p><p>#include &lt;numeric&gt;</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;functional&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  int a[] = { 1, 1, 2, 2, 3, 5, 7, 9, 11, 13 };</p><p>  const int asz = sizeof a / sizeof a[0];</p><p>  print(a, a + asz, "a", " ");</p><p>  int r = accumulate(a, a + asz, 0);</p><p>  cout &lt;&lt; "accumulate 1: " &lt;&lt; r &lt;&lt; endl;</p><p>  // Should produce the same result:</p><p>  r = accumulate(a, a + asz, 0, plus&lt;int&gt;());</p><p>  cout &lt;&lt; "accumulate 2: " &lt;&lt; r &lt;&lt; endl;</p><p>  int b[] = { 1, 2, 3, 4, 1, 2, 3, 4, 1, 2 };</p><p>  print(b, b + sizeof b / sizeof b[0], "b", " ");</p><p>  r = inner_product(a, a + asz, b, 0);</p><p>  cout &lt;&lt; "inner_product 1: " &lt;&lt; r &lt;&lt; endl;</p><p>  // Should produce the same result:</p><p>  r = inner_product(a, a + asz, b, 0,</p><p>    plus&lt;int&gt;(), multiplies&lt;int&gt;());</p><p>  cout &lt;&lt; "inner_product 2: " &lt;&lt; r &lt;&lt; endl;</p><p>  int* it = partial_sum(a, a + asz, b);</p><p>  print(b, it, "partial_sum 1", " ");</p><p>  // Should produce the same result:</p><p>  it = partial_sum(a, a + asz, b, plus&lt;int&gt;());</p><p>  print(b, it, "partial_sum 2", " ");</p><p>  it = adjacent_difference(a, a + asz, b);</p><p>  print(b, it, "adjacent_difference 1"," ");</p><p>  // Should produce the same result:</p><p>  it = adjacent_difference(a, a + asz, b,</p><p>    minus&lt;int&gt;());</p><p>  print(b, it, "adjacent_difference 2"," ");</p><p>} ///:~</p><empty-line/><p>Note that the return value of <strong>inner_product( )</strong> and <strong>partial_sum( )</strong> is the past-the-end iterator for the resulting sequence, so it is used as the second iterator in the <strong>print( )</strong> function.</p><p>Since the second form of each function allows you to provide your own function object, only the first form of the functions is purely "numeric." You could conceivably do some things that are not intuitively numeric with something like <strong>inner_product( )</strong>.</p></section></section></section><section><title><p>General utilities</p></title><p>Finally, here are some basic tools that are used with the other algorithms; you may or may not use them directly yourself.</p><p>&lt;utility&gt; struct <strong>pair</strong>; <strong>make_pair</strong>( );</p><p>This was described and used earlier in this chapter. A <strong>pair</strong> is simply a way to package two objects (which may be of different types) together into a single object. This is typically used when you need to return more than one object from a function, but it can also be used to create a container that holds <strong>pair </strong>objects or to pass more than one object as a single argument. You access the elements by saying <strong>p.first</strong> and <strong>p.second</strong>, in which <strong>p</strong> is the <strong>pair</strong> object. The function <strong>equal_range( )</strong>, described in the last chapter and in this one, returns its result as a <strong>pair</strong> of iterators. You can <strong>insert( )</strong> a <strong>pair</strong> directly into a <strong>map</strong> or <strong>multimap</strong>; a <strong>pair</strong> is the <strong>value_type</strong> for those containers.</p><p>If you want to create a <strong>pair </strong>"on the fly,", you typically use the template function <strong>make_pair( )</strong> rather than explicitly constructing a <strong>pair</strong> object.</p><p>&lt;iterator&gt; <strong>distance</strong>(InputIterator first, InputIterator last);</p><p>Tells you the number of elements between <strong>first</strong> and <strong>last</strong>. More precisely, it returns an integral value that tells you the number of times <strong>first</strong> must be incremented before it is equal to <strong>last</strong>. No dereferencing of the iterators occurs during this process.</p><p>&lt;iterator&gt; void <strong>advance</strong>(InputIterator&amp; i, Distance n);</p><p>Moves the iterator <strong>i</strong> forward by the value of <strong>n.</strong> (The iterator can also be moved backward for negative values of <strong>n</strong> if the iterator is also a bidirectional iterator.) This algorithm is aware of bidirectional iterators and will use the most efficient approach.</p><p>&lt;iterator&gt; back_insert_iterator&lt;Container&gt; <strong>back_inserter</strong>(Container&amp; x); front_insert_iterator&lt;Container&gt; <strong>front_inserter</strong>(Container&amp; x); insert_iterator&lt;Container&gt; <strong>inserter</strong>(Container&amp; x, Iterator i);</p><p>These functions are used to create iterators for the given containers that will insert elements into the container, rather than overwrite the existing elements in the container using <strong>operator= </strong>(which is the default behavior). Each type of iterator uses a different operation for insertion: <strong>back_insert_iterator</strong> uses <strong>push_back( )</strong>, <strong>front_insert_iterator</strong> uses <strong>push_front( ),</strong> and <strong>insert_iterator</strong> uses <strong>insert( )</strong> (and thus it can be used with the associative containers, while the other two can be used with sequence containers). These will be shown in some detail in the next chapter.</p><p>const LessThanComparable&amp; <strong>min</strong>(const LessThanComparable&amp; a, const LessThanComparable&amp; b); const T&amp; <strong>min</strong>(const T&amp; a, const T&amp; b, BinaryPredicate binary_pred);</p><p>Returns the lesser of its two arguments, or returns the first argument if the two are equivalent. The first version performs comparisons using <strong>operator&lt;,</strong> and the second passes both arguments to <strong>binary_pred</strong> to perform the comparison.</p><p>const LessThanComparable&amp; <strong>max</strong>(const LessThanComparable&amp; a,   const LessThanComparable&amp; b); const T&amp; <strong>max</strong>(const T&amp; a, const T&amp; b,   BinaryPredicate binary_pred);</p><p>Exactly like <strong>min( )</strong>, but returns the greater of its two arguments.</p><p>void <strong>swap</strong>(Assignable&amp; a, Assignable&amp; b); void <strong>iter_swap</strong>(ForwardIterator1 a, ForwardIterator2 b);</p><p>Exchanges the values of <strong>a</strong> and <strong>b</strong> using assignment. Note that all container classes use specialized versions of <strong>swap( )</strong> that are typically more efficient than this general version.</p><p>The <strong>iter_swap( )</strong> function swaps the values that its two arguments reference.</p></section></section><section><title><p>Creating your own STL-style algorithms</p></title><p>Once you become comfortable with the STL algorithm style, you can begin to create your own generic algorithms. Because these will conform to the conventions of all the other algorithms in the STL, they’re easy to use for programmers who are familiar with the STL, and thus they become a way to "extend the STL vocabulary."<sup>.</sup></p><p>The easiest way to approach the problem is to go to the <strong>&lt;algorithm&gt;</strong> header file, find something similar to what you need, and pattern your code after that.<sup>[90]</sup> (Virtually all STL implementations provide the code for the templates directly in the header files.)</p><p>Now that you’re comfortable with the ideas of the various iterator types, the actual implementation is quite straightforward. You can imagine creating an entire additional library of your own useful algorithms that follow the format of the STL<sup>.</sup></p><p>If you take a close look at the list of algorithms in the standard C++ library, you might notice a glaring omission: there is no <strong>copy_if( )</strong> algorithm. Although it’s true that you can accomplish the same thing with <strong>remove_copy_if( )</strong>, this is not quite as convenient because you have to invert the condition. (Remember, <strong>remove_copy_if( )</strong> only copies those elements that <emphasis>don’t</emphasis> match its predicate, in effect <emphasis>removing</emphasis> those that do.) You might be tempted to write a function object adapter that negates its predicate before passing it to <strong>remove_copy_if( )</strong>, by including a statement something like this:</p><p>// Assumes pred is the incoming condition</p><p>replace_copy_if(begin, end, not1(pred));</p><empty-line/><p>This seems reasonable, but when you remember that you want to be able to use predicates that are pointers to raw functions, you see why this won’t work—<strong>not1</strong> expects an adaptable function object. The only solution is to write a <strong>copy_if( )</strong> algorithm from scratch. Since you know from inspecting the other copy algorithms that conceptually you need separate iterators for input and output, the following example will do the job<sup>.</sup></p><p>//: C06:copy_if.h</p><p>// Roll your own STL-style algorithm</p><p>#ifndef COPY_IF_H</p><p>#define COPY_IF_H</p><empty-line/><p>template&lt;typename ForwardIter,</p><p>  typename OutputIter, typename UnaryPred&gt;</p><p>OutputIter copy_if(ForwardIter begin, ForwardIter end,</p><p>  OutputIter dest, UnaryPred f) {</p><p>  while(begin != end) {</p><p>    if(f(*begin))</p><p>      *dest++ = *begin;</p><p>    ++begin;</p><p>  }</p><p>  return dest;</p><p>}</p><p>#endif // COPY_IF_H ///:~</p><empty-line/></section><section><title><p>Summary</p></title><p>The goal of this chapter was to give you a practical understanding of the algorithms in the Standard Template Library. That is, to make you aware of and comfortable enough with the STL that you begin to use it on a regular basis (or, at least, to think of using it so you can come back here and hunt for the appropriate solution). It is powerful not only because it’s a reasonably complete library of tools, but also because it provides a vocabulary for thinking about problem solutions and because it is a framework for creating additional tools<sup>.</sup></p><p>Although this chapter did show some examples of creating your own tools, we did not go into the full depth of the theory of the STL that is necessary to completely understand all the STL nooks and crannies to allow you to create tools more sophisticated than those shown here. This was in part because of space limitations, but mostly because it is beyond the charter of this book; our goal here is to give you practical understanding that will affect your day-to-day programming skills<sup>.</sup></p><p>A number of books are dedicated solely to the STL (these are listed in the appendices), but we especially recommend Matthew H. Austern’s <emphasis>Generic Programming and the STL</emphasis> (Addison-Wesley, 1999) and Scott Meyers’s <emphasis>Effective STL</emphasis> (Addison-Wesley, 2002)<sup>.</sup></p></section><section><title><p>Exercises</p></title><p>             4.             Create a generator that returns the current value of <strong>clock( )</strong> (in <strong>&lt;ctime&gt;</strong>). Create a <strong>list&lt;clock_t&gt;,</strong> and fill it with your generator using <strong>generate_n( )</strong>. Remove any duplicates in the list and print it to <strong>cout</strong> using <strong>copy( )</strong>.</p><p>             4.             Using <strong>transform( )</strong> and <strong>toupper( )</strong> (in <strong>&lt;cctype&gt;</strong>), write a single function call that will convert a string to all uppercase letters.</p><p>             5.             Create a <strong>Sum</strong> function object template that will accumulate all the values in a range when used with <strong>for_each( )</strong>.</p><p>             6.             Write an anagram generator that takes a word as a command-line argument and produces all possible permutations of the letters.</p><p>             7.             Write a "sentence anagram generator" that takes a sentence as a command-line argument and produces all possible permutations of the words in the sentence. (It leaves the words alone and just moves them around.)</p><p>             8.             Create a class hierarchy with a base class <strong>B</strong> and a derived class <strong>D</strong>. Put a <strong>virtual</strong> member function <strong>void f( )</strong> in <strong>B</strong> such that it will print a message indicating that <strong>B</strong>’s <strong>f( )</strong> was called, and redefine this function for <strong>D</strong> to print a different message. Create a <strong>vector&lt;B*&gt;,</strong> and fill it with <strong>B</strong> and <strong>D</strong> objects. Use <strong>for_each( )</strong> to call <strong>f( )</strong> for each of the objects in your vector.</p><p>             9.             Modify <strong>FunctionObjects.cpp</strong> so that it uses <strong>float</strong> instead of <strong>int</strong>.</p><p>        10.             Modify <strong>FunctionObjects.cpp</strong> so that it templatizes the main body of tests so you can choose which type you’re going to test. (You’ll have to pull most of <strong>main( )</strong> out into a separate template function.)</p><p>         11.             Write a program that takes an integer as a command line argument and finds all of its factors.</p><p>         12.             Write a program that takes as a command-line argument the name of a text file. Open this file and read it a word at a time (hint: use <strong>&gt;&gt;</strong>). Store each word into a <strong>vector&lt;string&gt;</strong>. Force all the words to lowercase, sort them, remove all the duplicates, and print the results.</p><p>         13.             Write a program that finds all the words that are in common between two input files, using <strong>set_intersection( )</strong>. Change it to show the words that are not in common, using <strong>set_symmetric_difference( )</strong>.</p><p>         14.             Create a program that, given an integer on the command line, creates a "factorial table" of all the factorials up to and including the number on the command line. To do this, write a generator to fill a <strong>vector&lt;int&gt;</strong>, and then use <strong>partial_sum( )</strong> with a standard function object.</p><p>         15.             Modify <strong>CalcInventory.cpp</strong> so that it will find all the objects that have a quantity that’s less than a certain amount. Provide this amount as a command-line argument, and use <strong>copy_if( )</strong> and <strong>bind2nd( )</strong> to create the collection of values less than the target value.</p><p>         16.             Use <strong>UrandGen( )</strong> to generate 100 numbers. (The size of the numbers does not matter.) Find which numbers in your range are congruent mod 23 (meaning they have the same remainder when divided by 23). Manually pick a random number yourself, and find if that number is in your range by dividing each number in the list by your number and checking if the result is 1 instead of just using <strong>find( )</strong> with your value.</p><p>         17.             Fill a <strong>vector&lt;double&gt;</strong> with numbers representing angles in radians. Using function object composition, take the sine of all the elements in your vector (see <strong>&lt;cmath&gt;</strong>).</p><p>         18.             Test the speed of your computer. Call <strong>srand(time(0))</strong>, then make an array of random numbers. Call <strong>srand(time(0))</strong> again and generate the same number of random numbers in a second array. Use <strong>equal( )</strong> to see if the arrays are the same. (If your computer is fast enough, <strong>time(0)</strong> will return the same value both times it is called.) If the arrays are not the same, sort them and use <strong>mismatch( )</strong> to see where they differ. If they are the same, increase the length of your array and try again.</p><p>         19.             Create an STL-style algorithm <strong>transform_if( )</strong> following the first form of <strong>transform( )</strong> that performs transformations only on objects that satisfy a unary predicate. Objects that don’t satisfy the predicate are omitted from the result. It needs to return a new "end" iterator.</p><p>        20.             Create an STL-style algorithm that is an overloaded version of <strong>for_each( )</strong> which follows the second form of <strong>transform( )</strong> and takes two input ranges so it can pass the objects of the second input range a to a binary function that it applies to each object of the first range.</p><p>         21.             Create a <strong>Matrix</strong> class that is made from a <strong>vector&lt;vector&lt;int&gt; &gt;</strong>. Provide it with a friend <strong>ostream&amp; operator&lt;&lt;(ostream&amp;, const Matrix&amp;)</strong> to display the matrix. Create the following binary operations using the STL function objects where possible: <strong>operator+(const Matrix&amp;, const Matrix&amp;)</strong> for matrix addition, <strong>operator*(const Matrix&amp;, const vector&lt;int&gt;&amp;)</strong> for multiplying a matrix by a vector, and <strong>operator*(const Matrix&amp;, const Matrix&amp;)</strong> for matrix multiplication. (You might need to look up the mathematical meanings of the matrix operations if you don’t remember them.) Demonstrate each.</p><p>        22.             Using the characters "~`!@#$%^&amp;*()_-+=}{[]|\:;"'&lt;.&gt;,?/", generate a codebook using an input file given on the command line as a dictionary of words. Don't worry about stripping off the non-alphabetic characters nor worry about case of the words in the dictionary file. Map each permutation of the character string to a word such as the following: "=')/%[}]|{*@?!"`,;&gt;&amp;^-~_:$+.#(&lt;\"   apple "|]\~&gt;#.+%(/-_[`':;=}{*"$^!&amp;?),@&lt;"   carrot "@=~['].\/&lt;-`&gt;#*)^%+,";&amp;?!_{:|$}("   Carrot etc. Make sure that no duplicate codes or words exist in your code book. Use <strong>lexicographical_compare( )</strong> to perform a sort on the codes. Use your code book to encode the dictionary file. Decode your encoding of the dictionary file, and make sure you get the same contents back.</p><p>        23.             Using the following names:</p><empty-line/><p>Jon Brittle</p><p>Jane Brittle</p><p>Mike Brittle</p><p>Sharon Brittle</p><p>George Jensen</p><p>Evelyn Jensen</p><empty-line/><p>Find all the possible ways to arrange them for a wedding picture.</p><p>        24.             After being separated for one picture, the bride and groom decided they wanted to be together for all of them. Find all the possible ways to arrange the people for the picture if the bride and groom (Jon Brittle and Jane Brittle) are to be next to each other.<strong>&lt;/#&gt;&lt;#TIC2V2_CHAPTER8_I350&gt;</strong></p><p>        25.             A travel company wants to find out the average number of days people take to travel from one end of the continent to another. The problem is that in the survey, some people did not take a direct route and took much longer than is needed (such unusual data points are called "outliers"). Using the following generator following, generate travel days into a vector. Use <strong>remove_if( )</strong> to remove all the outliers in your vector. Take the average of the data in the vector to find out how long people generally take to travel.</p><empty-line/><p>int travelTime() {</p><p>        // The "outlier"</p><p>        if(rand() % 10 == 0)</p><p>          return rand() % 100;</p><p>        // Regular route</p><p>        return rand() % 10 + 10;</p><p>}</p><p><strong>&lt;/#&gt;&lt;#TIC2V2_CHAPTER8_I353&gt;</strong></p><p>        26.             Determine how much faster <strong>binary_search( )</strong> is to <strong>find( )</strong> when it comes to searching <emphasis>sorted</emphasis> ranges.&lt;/#&gt;&lt;#TIC2V2_CHAPTER8_I354&gt;</p><p>         27.             The army wants to recruit people from its selective service list. They have decided to recruit those that signed up for the service in 1997 starting from the oldest down to the youngest. Generate an arbitrary amount of people (give them data members such as <strong>age</strong> and <strong>yearEnrolled</strong>) into a vector. Partition the vector so that those who enrolled in 1997 are ordered at the beginning of the list, starting from the youngest to the oldest, and leave the remaining part of the list sorted according to age.</p><p>        28.             Make a <strong>class</strong> called Town with population, altitude, and weather data members. Make the weather an <strong>enum</strong> with <strong>{ RAINY, SNOWY, CLOUDY, CLEAR }</strong>. Make a class that generates Town objects. Generate town names (whether they make sense or not it doesn’t matter) or pull them off the internet. Ensure that the whole town name is lower case and there are no duplicate names. For simplicity, we recommend keeping your town names to one word. For the population, altitudes, and weather fields, make a generator that will randomly generate weather conditions, populations within the range [100 to 1,000,000) and altitudes between [0, 8000) feet. Fill a vector with your Town objects. Rewrite the vector out to a new file called Towns.txt.</p><p>        29.             There was a baby boom, resulting in a 10% population increase in every town. Update your town data using <strong>transform( )</strong>, rewrite your data back out to file.</p><p>        30.             Find the towns with the highest and lowest population. Temporarily implement <strong>operator&lt;</strong> for your town object for this exercise. Also try implementing a function that returns true if its first parameter is less than its second. Use it as a predicate to call the algorithm you use.</p><p>         31.             Find all the towns within the altitudes 2500-3500 feet inclusive. Implement equality operators for the <strong>Town</strong> class as needed.</p><p>        32.             We need to place an airport in a certain altitude, but location is not a problem. Organize your list of towns so that there are no duplicate (duplicate meaning that no two altitudes are within the same 100 ft range. Such classes would include [100, 199), [200, 199), etc. altitudes. Sort this list in ascending order in at least two different ways using the function objects in <strong>&lt;functional&gt;</strong>. Do the same for descending order. Implement relational operators for <strong>Town</strong> as needed.</p><p>        33.             Generate an arbitrary number of random numbers in a stack-based array. Use <strong>max_element( )</strong> to find the largest number in array. Swap it with the number at the end of your array. Find the next largest number and place it in the array in the position before the previous number. Continue doing this until all elements have been moved. When the algorithm is complete, you will have a sorted array. (This is a "selection sort".)</p><p>        34.             Write a program that will take phone numbers from a file (that also contains names and other suitable information) and change the numbers that begin with 222 to 863. Be sure to save the old numbers. The file format is be as follows:</p><p>222 8945</p><p>756 3920</p><p>222 8432</p><p>etc.</p><p>        35.             Write a program that given a last name will find everyone with that last name with his or her corresponding phone number. Use the algorithms that deal with ranges (<strong>lower_bound</strong>, <strong>upper_bound</strong>, <strong>equal_range</strong>, etc.). Sort with the last name acting as a primary key and the first name acting as a secondary key. Assume that you will read the names and numbers from a file where the format will be as follows. (Be sure to order them so that the last names are ordered, and the first names are ordered within the last names.):</p><empty-line/><p>John Doe             345 9483</p><p>Nick Bonham    349 2930</p><p>Jane Doe              283 2819</p><empty-line/><p>        36.             Given a file with data similar to the following, pull all the state acronyms from the file and put them in a separate file. (Note that you can’t depend on the line number for the type of data. The data is on random lines.)</p><empty-line/><p>ALABAMA</p><p>AL</p><p>AK</p><p>ALASKA</p><p>ARIZONA</p><p>AZ</p><p>ARKANSAS</p><p>AR</p><p>CA</p><p>CALIFORNIA</p><p>CO</p><p>COLORADO</p><p>etc.</p><empty-line/><p>When complete, you should have a file with all the state acronyms which are:</p><p>AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY</p><p>         37.             Make an <strong>Employee </strong>class with two data members: <strong>hours </strong>and <strong>hourlyPay</strong>. Employee shall also have a <strong>calcSalary( )</strong> function which returns the pay for that employee. Generate random hourly pay and hours for an arbitrary amount of employees. Keep a <strong>vector&lt;Employee*&gt;</strong>. Find out how much money the company is going to spend for this pay period.</p><p>        38.             Race <strong>sort( ), partial_sort( ), </strong>and <strong>nth_element( )</strong> against each other and find out if it’s really worth the time saved to use one of the weaker sorts if they’re all that’s needed.</p></section></section><section><title><p>7: Generic containers</p></title><section><p><emphasis>Container classes </emphasis>are the solution to a specific kind of code reuse problem. They are building blocks used to create object-oriented programs—they make the internals of a program much easier to construct.</p><p>A container class describes an object that holds other objects. Container classes are so important that they were considered fundamental to early object-oriented languages. In Smalltalk, for example, programmers think of the language as the program translator together with the class library, and a critical part of that library is the container classes. So it became natural that C++ compiler vendors also include a container class library. You’ll note that the <strong>vector</strong> was so useful that it was introduced in its simplest form early in Volume 1 of this book.</p><p>Like many other early C++ libraries, early container class libraries followed Smalltalk’s <emphasis>object-based hierarchy</emphasis>, which worked well for Smalltalk, but turned out to be awkward and difficult to use in C++. Another approach was required.</p><p>The C++ approach to containers is based, of course, on templates. The containers in the standard C++ library represent a broad range of data structures designed to work well with the standard algorithms and to meet common software development needs.</p></section><section><title><p>Containers and iterators</p></title><section><p>If you don’t know how many objects you’re going to need to solve a particular problem, or how long they will last, you also don’t know ahead of time how to store those objects. How can you know how much space to create? You don’t until run time<sup>.</sup></p><p>The solution to most problems in object-oriented design seems simple: you create another type of object. For the storage problem, the new type of object holds other objects or pointers to objects. This new type of object, which is typically referred to in C++ as a <emphasis>container</emphasis> (also called a <emphasis>collection</emphasis> in some languages), expands itself whenever necessary to accommodate everything you place inside it. You don’t need to know ahead of time how many objects you’re going to place in a container; you just create a container object and let it take care of the details<sup>.</sup></p><p>Fortunately, a good object-oriented programming language comes with a set of containers. In C++, it’s the Standard Template Library. In some libraries, a generic container is considered good enough for all needs, and in others (C++ in particular) the library has different types of containers for different needs: a vector for consistent access to all elements, and a linked list for consistent insertion at all positions, and many more, so you can choose the particular type that fits your needs<sup>.</sup></p><p>All containers have some way to put things in and get things out. The way you place something into a container is fairly obvious. There’s a function called "push" or "add" or a similar name. Fetching things out of a container is not always as apparent; if an entity is array-like, such as a vector, you might be able to use an indexing operator or function. But in many situations this doesn’t make sense. Also, a single-selection function is restrictive. What if you want to manipulate or compare a group of elements in the container?<sup>.</sup></p><p>The solution for flexible element access is an <emphasis>iterator</emphasis>, an object whose job is to select the elements within a container and present them to the user of the iterator. As a class, an iterator also provides a level of abstraction, which you can use to separate the details of the container from the code that’s accessing that container. The container, via the iterator, is seen as a sequence. The iterator lets you traverse that sequence without worrying about the underlying structure—that is, whether it’s a vector, a linked list, a set, or something else. This gives you the flexibility to easily change the underlying data structure without disturbing the code in your program that traverses the container. Separating iteration from the control of the container traversed also allows having multiple iterators simultaneously<sup>.</sup></p><p>From a design standpoint, all you really want is a sequence that can be manipulated to solve your problem. If a single type of sequence satisfied all your needs, there’d be no reason to have different kinds. You need a choice of containers for two reasons. First, containers provide different types of interfaces and external behavior. A stack has an interface and a behavior that is different from that of a queue, which is different from that of a set or a list. One of these might provide a more flexible solution to your problem than the other. Second, different containers have different efficiencies for certain operations. Compare a vector to a list, as an example. Both are simple sequences that can have nearly identical interfaces and external behaviors. But certain operations can have radically different costs. Randomly accessing elements in a vector is a constant-time operation; it takes the same amount of time regardless of the element you select. However, it is expensive to move through a linked list to randomly access an element, and it takes longer to find an element if it is farther down the list. On the other hand, if you want to insert an element in the middle of a sequence, it’s much cheaper in a list than in a vector. The efficiencies of these and other operations depend on the underlying structure of the sequence. In the design phase, you might start with a list and, when tuning for performance, change to a vector, or vice-versa. Because of iterators, code that merely traverses sequences is insulated from changes in the underlying sequence implementation<sup>.</sup></p><p>Remember that a container is only a storage cabinet in which to put objects. If that cabinet solves all your needs, it probably doesn’t really matter <emphasis>how</emphasis> it is implemented. If you’re working in a programming environment that has built-in overhead due to other factors, the cost difference between a vector and a linked list might not matter. You might need only one type of sequence. You can even imagine the "perfect" container abstraction, which can automatically change its underlying implementation according to the way it is used<sup>.</sup></p></section><section><title><p>STL reference documentation</p></title><p>As in the previous chapter, you will notice that this chapter does not contain exhaustive documentation describing each of the member functions in each STL container. Although we describe the member functions we use, we’ve left the full descriptions to others. We recommend the online resources available for the Dinkumware, Silicon Graphics, and STLPort STL implementations.<sup>[91]</sup></p></section></section><section><title><p>A first look</p></title><section><p>Here’s an example using the <strong>set</strong> class template, a container modeled after a traditional mathematical set and which does not accept duplicate values. This simple <strong>set</strong> was created to work with <strong>int</strong>s:<sup>.</sup></p><p>//: C07:Intset.cpp</p><p>// Simple use of STL set</p><p>#include &lt;cassert&gt;</p><p>#include &lt;set&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  set&lt;int&gt; intset;</p><p>    for(int i = 0; i &lt; 25; i++)</p><p>      for(int j = 0; j &lt; 10; j++)</p><p>        // Try to insert duplicates:</p><p>        intset.insert(j);</p><p>  assert(intset.size() == 10);</p><p>} ///:~</p><empty-line/><p>The <strong>insert( )</strong> member does all the work: it attempts to insert an element and ignores it if it’s already there. Often the only activities involved in using a set are simply insertion and testing to see whether it contains the element. You can also form a union, an intersection, or a difference of sets and test to see if one set is a subset of another. In this example, the values 0–9 are inserted into the set 25 times, but only the 10 unique instances are accepted<sup>.</sup></p><p>Now consider taking the form of <strong>Intset.cpp</strong> and modifying it to display a list of the words used in a document. The solution becomes remarkably simple<sup>.</sup></p><p>//: C07:WordSet.cpp</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;set&gt;</p><p>#include &lt;string&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>void wordSet(char* fileName) {</p><p>  ifstream source(fileName);</p><p>  assure(source, fileName);</p><p>  string word;</p><p>  set&lt;string&gt; words;</p><p>  while(source &gt;&gt; word)</p><p>    words.insert(word);</p><p>  copy(words.begin(), words.end(),</p><p>    ostream_iterator&lt;string&gt;(cout, "\n"));</p><p>  cout &lt;&lt; "Number of unique words:"</p><p>    &lt;&lt; words.size() &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  if(argc &gt; 1)</p><p>    wordSet(argv[1]);</p><p>  else</p><p>    wordSet("WordSet.cpp");</p><p>} ///:~</p><empty-line/><p>The only substantive difference here is that <strong>string</strong> is used instead of <strong>int</strong>. The words are pulled from a file, but the other operations are similar to those in <strong>Intset.cpp</strong>. Not only does the output reveal that duplicates have been ignored, but because of the way <strong>set</strong> is implemented, the words are automatically sorted<sup>.</sup></p><p>A set is an example of an <emphasis>associative container</emphasis>, one of the three categories of containers provided by the standard C++ library. The containers and their categories are summarized in the following table.</p><table><tr align="left"><td align="left" valign="top">Category</td><td align="left" valign="top">Containers</td></tr><tr align="left"><td align="left" valign="top">Simple Sequence Containers</td><td align="left" valign="top">vector, list, deque</td></tr><tr align="left"><td align="left" valign="top">Container Adapters</td><td align="left" valign="top">queue, stack, priority_queue</td></tr><tr align="left"><td align="left" valign="top">Associative Containers</td><td align="left" valign="top">set, map, multiset, multimap</td></tr></table><empty-line/><p>All the containers in the standard library hold objects and expand their resources as needed. The key difference between one container and another is the way the objects are stored in memory and what operations are available to the user<sup>.</sup></p><p>A <strong>vector</strong>, as you already know, is a linear sequence that allows rapid random access to its elements. However, it’s expensive to insert an element in the middle of a co-located sequence like a vector, just as it is with an array. A <strong>deque</strong> (double-ended-queue, pronounced "deck") also allows random access that’s nearly as fast as <strong>vector</strong>, but it’s significantly faster when it needs to allocate new storage, and you can easily add new elements at the front as well as the back of the sequence. A <strong>list</strong> is a doubly linked list, so it’s expensive to move around randomly but cheap to insert an element anywhere. Thus <strong>list</strong>, <strong>deque</strong> and <strong>vector</strong> are similar in their basic functionality (they all hold linear sequences), but different in the cost of their activities. So for your first shot at a program, you could choose any one and experiment with the others only if you’re tuning for efficiency<sup>.</sup></p><p>Many of the problems you set out to solve will only require a simple linear sequence such as a <strong>vector</strong>, <strong>deque,</strong> or <strong>list</strong>. All three have a member function <strong>push_back( )</strong> that you use to insert a new element at the back of the sequence (<strong>deque</strong> and <strong>list</strong> also have <strong>push_front( )</strong>).</p><p>But now how do you retrieve those elements? With a <strong>vector</strong> or <strong>deque</strong>, it is possible to use the indexing <strong>operator[ ]</strong>, but that doesn’t work with <strong>list</strong>. You can use iterators on all three sequences to access elements. Each container provides the appropriate type of iterator for accessing its elements<sup>.</sup></p><p>One more observation and then we’ll be ready for another example. Even though the containers hold objects by value (that is, they hold copies of whole objects), sometimes you’ll want to store pointers so that you can refer to objects from a hierarchy and therefore take advantage of the polymorphic behavior of the classes represented. Consider the classic "shape" example in which shapes have a set of common operations, and you have different types of shapes. Here’s what it looks like using the STL <strong>vector</strong> to hold pointers to various <strong>Shape</strong> types created on the heap:<sup>.</sup></p><p>//: C07:Stlshape.cpp</p><p>// Simple shapes w/ STL</p><p>#include &lt;vector&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Shape {</p><p>public:</p><p>  virtual void draw() = 0;</p><p>  virtual ~Shape() {};</p><p>};</p><empty-line/><p>class Circle : public Shape {</p><p>public:</p><p>  void draw() { cout &lt;&lt; "Circle::draw\n"; }</p><p>  ~Circle() { cout &lt;&lt; "~Circle\n"; }</p><p>};</p><empty-line/><p>class Triangle : public Shape {</p><p>public:</p><p>  void draw() { cout &lt;&lt; "Triangle::draw\n"; }</p><p>  ~Triangle() { cout &lt;&lt; "~Triangle\n"; }</p><p>};</p><empty-line/><p>class Square : public Shape {</p><p>public:</p><p>  void draw() { cout &lt;&lt; "Square::draw\n"; }</p><p>  ~Square() { cout &lt;&lt; "~Square\n"; }</p><p>};</p><empty-line/><p>typedef std::vector&lt;Shape*&gt; Container;</p><p>typedef Container::iterator Iter;</p><empty-line/><p>int main() {</p><p>  Container shapes;</p><p>  shapes.push_back(new Circle);</p><p>  shapes.push_back(new Square);</p><p>  shapes.push_back(new Triangle);</p><p>  for(Iter i = shapes.begin();</p><p>      i != shapes.end(); i++)</p><p>    (*i)-&gt;draw();</p><p>  // ... Sometime later:</p><p>  for(Iter j = shapes.begin();</p><p>      j != shapes.end(); j++)</p><p>    delete *j;</p><p>} ///:~</p><empty-line/><p>The creation of <strong>Shape</strong>, <strong>Circle</strong>, <strong>Square,</strong> and <strong>Triangle</strong> should be fairly familiar. <strong>Shape</strong> is a pure abstract base class (because of the <emphasis>pure specifier</emphasis><strong>=0</strong>) that defines the interface for all types of <strong>shapes</strong>. The derived classes redefine the <strong>virtual</strong> function <strong>draw( )</strong> to perform the appropriate operation. Now we’d like to create a bunch of different types of <strong>Shape</strong> objects, but where to put them? In an STL container, of course. For convenience, this <strong>typedef</strong>:</p><p>typedef std::vector&lt;Shape*&gt; Container;</p><empty-line/><p>creates an alias for a <strong>vector</strong> of <strong>Shape*</strong>, and this <strong>typedef</strong>:</p><p>typedef Container::iterator Iter;</p><empty-line/><p>uses that alias to create another one, for <strong>vector&lt;Shape*&gt;::iterator</strong>. Notice that the <strong>container</strong> type name must be used to produce the appropriate iterator, which is defined as a nested class. Although there are different types of iterators (forward, bidirectional, reverse, and so on), they all have the same basic interface: you can increment them with <strong>++</strong>, you can dereference them to produce the object they’re currently selecting, and you can test them to see if they’re at the end of the sequence. That’s what you’ll want to do 90 percent of the time. And that’s what is done in the previous example: after a container is created, it’s filled with different types of <strong>Shape</strong> pointers. Notice that the upcast happens as the <strong>Circle</strong>, <strong>Square,</strong> or <strong>Rectangle</strong> pointer is added to the <strong>shapes</strong> container, which doesn’t know about those specific types but instead holds only <strong>Shape*</strong>. As soon as the pointer is added to the container, it loses its specific identity and becomes an anonymous <strong>Shape*</strong>. This is exactly what we want: toss them all in and let polymorphism sort it out<sup>.</sup></p><p>The first <strong>for</strong> loop creates an iterator and sets it to the beginning of the sequence by calling the <strong>begin( )</strong> member function for the container. All containers have <strong>begin( )</strong> and <strong>end( )</strong> member functions that produce an iterator selecting, respectively, the beginning of the sequence and one past the end of the sequence. To test to see if you’re done, you make sure you’re <strong>!=</strong> to the iterator produced by <strong>end( )</strong>. Not <strong>&lt;</strong> or <strong>&lt;=</strong>. The only test that works is <strong>!=</strong>. So it’s common to write a loop like:<sup>.</sup></p><p>for(Iter i = shapes.begin(); i != shapes.end(); i++)</p><empty-line/><p>This says "take me through every element in the sequence."<sup>.</sup></p><p>What do you do with the iterator to produce the element it’s selecting? You dereference it using (what else?) the ‘<strong>*</strong>’ (which is actually an overloaded operator). What you get back is whatever the container is holding. This container holds <strong>Shape*</strong>, so that’s what <strong>*i</strong> produces. If you want to call a <strong>Shape</strong> member function, you must do so with the <strong>-&gt;</strong> operator, so you write the line:<sup>.</sup></p><p>(*i)-&gt;draw();</p><empty-line/><p>This calls the <strong>draw( )</strong> function for the <strong>Shape*</strong> the iterator is currently selecting. The parentheses are ugly but necessary to produce the desired operator precedence<sup>.</sup></p><p>As they are destroyed or in other cases where the pointers are removed, the STL containers <emphasis>do not</emphasis> automatically call <strong>delete</strong> for the pointers they contain. If you create an object on the heap with <strong>new</strong> and place its pointer in a container, the container can’t tell if that pointer is also placed inside another container, nor if it refers to heap memory in the first place. As always, you are responsible for managing your own heap allocations. The last lines in the program move through and delete every object in the container so that proper cleanup occurs<sup>.</sup></p><p>You can change the type of container that this program uses with two lines. Instead of including <strong>&lt;vector&gt;</strong>, you include <strong>&lt;list&gt;</strong>, and in the first <strong>typedef</strong> you say:<sup>.</sup></p><p>typedef std::list&lt;Shape*&gt; Container;</p><empty-line/><p>instead of using a <strong>vector</strong>. Everything else goes untouched. This is possible not because of an interface enforced by inheritance (there is little inheritance in the STL, which may come as a surprise), but because the interface is enforced by a convention adopted by the designers of the STL, precisely so you could perform this kind of interchange. Now you can easily switch between <strong>vector</strong> and <strong>list</strong> or any other container that supports the same interface and see which one works fastest for your needs<sup>.</sup></p></section><section><title><p>Containers of strings</p></title><p>In the previous example, at the end of <strong>main( )</strong> it was necessary to move through the whole list and <strong>delete</strong> all the <strong>Shape</strong> pointers:<sup>.</sup></p><p>for(Iter j = shapes.begin();</p><p>      j != shapes.end(); j++)</p><p>    delete *j;</p><empty-line/><p>This highlights what could be seen as an oversight in the STL: there’s no facility in any of the STL containers to automatically <strong>delete</strong> the pointers they contain, so you must do it by hand. It’s as if the assumption of the STL designers was that containers of pointers weren’t an interesting problem<sup>.</sup></p><p>Automatically deleting a pointer turns out to be a rather aggressive thing to do because of the <emphasis>multiple membership</emphasis> problem. If a container holds a pointer to an object, it’s not unlikely that pointer could also be in another container. A pointer to an <strong>Aluminum</strong> object in a list of <strong>Trash</strong> pointers could also reside in a list of <strong>Aluminum</strong> pointers. If that happens, which list is responsible for cleaning up that object—that is, which list "owns" the object?<sup>.</sup></p><p>This question is virtually eliminated if the object rather than a pointer resides in the list. Then it seems clear that when the list is destroyed, the objects it contains must also be destroyed. Here, the STL shines, as you can see when creating a container of <strong>string</strong> objects. The following example stores each incoming line as a <strong>string</strong> in a <strong>vector&lt;string&gt;</strong>:</p><p>//: C07:StringVector.cpp</p><p>// A vector of strings</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  char* fname = "StringVector.cpp";</p><p>  if(argc &gt; 1) fname = argv[1];</p><p>  ifstream in(fname);</p><p>  assure(in, fname);</p><p>  vector&lt;string&gt; strings;</p><p>  string line;</p><p>  while(getline(in, line))</p><p>    strings.push_back(line);</p><p>  // Do something to the strings...</p><p>  int i = 1;</p><p>  vector&lt;string&gt;::iterator w;</p><p>  for(w = strings.begin();</p><p>      w != strings.end(); w++) {</p><p>    ostringstream ss;</p><p>    ss &lt;&lt; i++;</p><p>    *w = ss.str() + ": " + *w;</p><p>  }</p><p>  // Now send them out:</p><p>  copy(strings.begin(), strings.end(),</p><p>    ostream_iterator&lt;string&gt;(cout, "\n"));</p><p>  // Since they aren't pointers, string</p><p>  // objects clean themselves up!</p><p>} ///:~</p><empty-line/><p>Once the <strong>vector&lt;string&gt; </strong>called <strong>strings</strong> is created, each line in the file is read into a <strong>string</strong> and put in the <strong>vector</strong>:<sup>.</sup></p><p>  while(getline(in, line))</p><p>    strings.push_back(line);</p><empty-line/><p>The operation that’s being performed on this file is to add line numbers. A <strong>stringstream</strong> provides easy conversion from an <strong>int</strong> to a <strong>string</strong> of characters representing that <strong>int</strong><sup><strong>.</strong></sup></p><p>Assembling <strong>string</strong> objects is quite easy, since <strong>operator+</strong> is overloaded. Sensibly enough, the iterator <strong>w</strong> can be dereferenced to produce a string that can be used as both an rvalue <emphasis>and</emphasis> an lvalue:<sup>.</sup></p><p>*w = ss.str() + ": " + *w;</p><empty-line/><p>You may be surprised that you can assign back into the container via the iterator , but it’s a tribute to the careful design of the STL<sup>.</sup></p><p>Because the <strong>vector&lt;string&gt;</strong> contains the objects themselves, a number of interesting things take place. First, no explicit cleanup of the <strong>string</strong> objects on your part is necessary. Even if you were to put addresses of the <strong>string</strong> objects as pointers into <emphasis>other</emphasis> containers, it’s clear that <strong>strings</strong> is the "master list" and maintains ownership of the objects<sup>.</sup></p><p>Second, you are effectively using dynamic object creation, and yet you never use <strong>new</strong> or <strong>delete</strong>! That’s because, somehow, it’s all taken care of for you by the <strong>vector</strong> because it stores <emphasis>copies</emphasis> of the objects you give it. Thus your coding is significantly cleaned up<sup>.</sup></p></section><section><title><p>Inheriting from STL containers</p></title><p>The power of instantly creating a sequence of elements is amazing, and it makes you realize how much time you may have spent (or rather wasted) in the past solving this particular problem. For example, many utility programs involve reading a file into memory, modifying the file, and writing it back out to disk. You might as well take the functionality in <strong>StringVector.cpp</strong> and package it into a class for later reuse<sup>.</sup></p><p>Now the question is: do you create a member object of type <strong>vector</strong>, or do you inherit? A general object-oriented design guideline is to prefer composition (member objects) over inheritance, but the standard algorithms expect sequences that implement a specified interface, so inheritance is often called for<sup>.</sup></p><p>//: C07:FileEditor.h</p><p>// File editor tool</p><p>#ifndef FILEEDITOR_H</p><p>#define FILEEDITOR_H</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><empty-line/><p>class FileEditor :</p><p>  public std::vector&lt;std::string&gt; {</p><p>public:</p><p>  void open(const char* filename);</p><p>  FileEditor(const char* filename) {</p><p>    open(filename);</p><p>  }</p><p>  FileEditor() {};</p><p>  void write(std::ostream&amp; out = std::cout);</p><p>};</p><p>#endif // FILEEDITOR_H ///:~</p><empty-line/><p>Note the careful avoidance of a global <strong>using namespace std</strong> statement here, to prevent the opening of the <strong>std</strong> namespace in every file that includes this header<sup>.</sup></p><p>The constructor opens the file and reads it into the <strong>FileEditor</strong>, and <strong>write( )</strong> puts the <strong>vector</strong> of <strong>string</strong> onto any <strong>ostream</strong>. Notice in <strong>write( ) </strong>that you can have a default argument for the reference<sup>.</sup></p><p>The implementation is quite simple:<sup>.</sup></p><p>//: C07:FileEditor.cpp {O}</p><p>#include "FileEditor.h"</p><p>#include &lt;fstream&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>void FileEditor::open(const char* filename) {</p><p>  ifstream in(filename);</p><p>  assure(in, filename);</p><p>  string line;</p><p>  while(getline(in, line))</p><p>    push_back(line);</p><p>}</p><empty-line/><p>// Could also use copy() here:</p><p>void FileEditor::write(ostream&amp; out) {</p><p>  for(iterator w = begin();  w != end(); w++)</p><p>    out &lt;&lt; *w &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The functions from <strong>StringVector.cpp</strong> are simply repackaged. Often this is the way classes evolve—you start by creating a program to solve a particular application and then discover some commonly used functionality within the program that can be turned into a class<sup>.</sup></p><p>The line-numbering program can now be rewritten using <strong>FileEditor</strong>:<sup>.</sup></p><p>//: C07:FEditTest.cpp</p><p>//{L} FileEditor</p><p>// Test the FileEditor tool</p><p>#include &lt;sstream&gt;</p><p>#include "FileEditor.h"</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  FileEditor file;</p><p>  if(argc &gt; 1) {</p><p>    file.open(argv[1]);</p><p>  } else {</p><p>    file.open("FEditTest.cpp");</p><p>  }</p><p>  // Do something to the lines...</p><p>  int i = 1;</p><p>  FileEditor::iterator w = file.begin();</p><p>  while(w != file.end()) {</p><p>    ostringstream ss;</p><p>    ss &lt;&lt; i++;</p><p>    *w = ss.str() + ": " + *w;</p><p>    w++;</p><p>  }</p><p>  // Now send them to cout:</p><p>  file.write();</p><p>} ///:~</p><p>Now the operation of reading the file is in the constructor:<sup>.</sup></p><p>FileEditor file(argv[1]);</p><empty-line/><p>(or in the <strong>open( ) </strong>member function), and writing happens in the single line (which defaults to sending the output to <strong>cout</strong>):</p><p>file.write();</p><empty-line/><p>The bulk of the program is involved with actually modifying the file in memory.</p></section></section><section><title><p>A plethora of iterators</p></title><section><p>As mentioned earlier in this and the previous chapter, an iterator is an abstraction that allows code to be generic, that is, to work with different types of containers without knowing the underlying structure of those containers. Most containers support iterators.<a l:href="#n92" type="note">[92]</a> You can always say:<sup>.</sup></p><p>&lt;ContainerType&gt;::iterator</p><p>&lt;ContainerType&gt;::const_iterator</p><empty-line/><p>to produce the types of the iterators produced by that container. Every container has a <strong>begin( )</strong> member function that produces an iterator indicating the beginning of the elements in the container, and an <strong>end( )</strong> member function that produces an iterator which is the as the <emphasis>past-the-end </emphasis>marker of the container. If the container is <strong>const</strong>&#xB8; <strong>begin( )</strong> and <strong>end( )</strong> produce <strong>const</strong> iterators, which disallow changing the elements pointed to (because the appropriate operators are <strong>const</strong>)<sup>.</sup></p><p>All iterators can advance within their sequence (via <strong>operator++</strong>) and allow <strong>==</strong> and <strong>!=</strong> comparisons. Thus, to move an iterator <strong>it</strong> forward without running it off the end, you say something like:<sup>.</sup></p><p>while(it != pastEnd) {</p><p>  // Do something</p><p>  it++;</p><p>}</p><empty-line/><p>in which <strong>pastEnd</strong> is the past-the-end marker produced by the container’s <strong>end( )</strong> member function<sup>.</sup></p><p>An iterator can be used to produce the element that it is currently selecting within a container through the dereferencing operator (<strong>operator*</strong>). This can take two forms. If <strong>it </strong>is an iterator and <strong>f( ) </strong>is a member function of the objects held in the container that the iterator is pointing within, you can say either:<sup>.</sup></p><p>(*it).f();</p><empty-line/><p>or<sup>.</sup></p><p>it-&gt;f();</p><empty-line/><p>Knowing this, you can create a template that works with any container. Here, the <strong>apply( )</strong> function template calls a member function for every object in the container, using a pointer to member that is passed as an argument:<sup>.</sup></p><p>//: C07:Apply.cpp</p><p>// Using simple iteration</p><p>#include &lt;iostream&gt;</p><p>#include &lt;vector&gt;</p><p>#include &lt;iterator&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class Cont, class PtrMemFun&gt;</p><p>void apply(Cont&amp; c, PtrMemFun f) {</p><p>  typename Cont::iterator it = c.begin();</p><p>  while(it != c.end()) {</p><p>    ((*it).*f)(); // Alternate form</p><p>    it++;</p><p>  }</p><p>}</p><empty-line/><p>class Z {</p><p>  int i;</p><p>public:</p><p>  Z(int ii) : i(ii) {}</p><p>  void g() { i++; }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Z&amp; z) {</p><p>    return os &lt;&lt; z.i;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  ostream_iterator&lt;Z&gt; out(cout, " ");</p><p>  vector&lt;Z&gt; vz;</p><p>  for(int i = 0; i &lt; 10; i++)</p><p>    vz.push_back(Z(i));</p><p>  copy(vz.begin(), vz.end(), out);</p><p>  cout &lt;&lt; endl;</p><p>  apply(vz, &amp;Z::g);</p><p>  copy(vz.begin(), vz.end(), out);</p><p>} ///:~</p><empty-line/><p>You can’t use <strong>operator-&gt;</strong> in this case, because the resulting statement would be</p><p>(it-&gt;*f)();</p><empty-line/><p>which attempts to use the iterator’s <strong>operator-&gt;*</strong>, which is not provided by the iterator classes.<a l:href="#n93" type="note">[93]</a></p><p>It is much easier to use either <strong>for_each( )</strong> or <strong>transform( )</strong> to apply functions to sequences anyway, as you saw in the previous chapter<sup>.</sup></p></section><section><title><p>Iterators in reversible containers</p></title><p>A container may also be <emphasis>reversible</emphasis>, which means that it can produce iterators that move backward from the end, as well as the iterators that move forward from the beginning. All standard containers support such bidirectional iteration<sup>.</sup></p><p>A reversible container has the member functions <strong>rbegin( )</strong> (to produce a <strong>reverse_iterator</strong> selecting the end) and <strong>rend( )</strong> (to produce a <strong>reverse_iterator</strong> indicating "one past the beginning"). If the container is <strong>const, rbegin( )</strong> and <strong>rend( )</strong> will produce <strong>const_reverse_iterator</strong>s.</p><p>The following example uses <strong>vector</strong>, but will work with all containers that support iteration:</p><p>//: C07:Reversible.cpp</p><p>// Using reversible containers</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  ifstream in("Reversible.cpp");</p><p>  assure(in, "Reversible.cpp");</p><p>  string line;</p><p>  vector&lt;string&gt; lines;</p><p>  while(getline(in, line))</p><p>    lines.push_back(line);</p><p>  for(vector&lt;string&gt;::reverse_iterator r = lines.rbegin();</p><p>      r != lines.rend(); r++)</p><p>    cout &lt;&lt; *r &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>You move backward through the container using the same syntax as moving forward through a container with an ordinary iterator.</p></section><section><title><p>Iterator categories</p></title><section><p>The iterators are classified into "categories" that describe their capabilities. The order in which they are generally described moves from the categories with the most restricted behavior to those with the most powerful behavior.</p></section><section><section><title><p>Input: read-only, one pass</p></title><p>The only predefined implementations of input iterators are <strong>istream_iterator</strong> and <strong>istreambuf_iterator</strong>, to read from an <strong>istream</strong>. As you can imagine, an input iterator can only be dereferenced once for each element that’s selected, just as you can only read a particular portion of an input stream once. They can only move forward. A special constructor defines the past-the-end value. In summary, you can dereference it for reading (once only for each value) and move it forward.</p></section><section><title><p>Output: write-only, one pass</p></title><p>This is the complement of an input iterator, but for writing rather than reading. The only predefined implementations of output iterators are <strong>ostream_iterator</strong> and <strong>ostreambuf_iterator</strong>, to write to an <strong>ostream</strong>, and the less commonly used <strong>raw_storage_iterator</strong>. Again, these can only be dereferenced once for each written value, and they can only move forward. There is no concept of a terminal past-the-end value for an output iterator. Summarizing, you can dereference it for writing (once only for each value) and move it forward.</p></section><section><title><p>Forward: multiple read/write</p></title><p>The forward iterator contains all the functionality of both the input iterator and the output iterator, plus you can dereference an iterator location multiple times, so you can read and write to a value multiple times. As the name implies, you can only move forward. There are no predefined iterators that are only forward iterators.</p></section><section><title><p>Bidirectional: operator--</p></title><p>The bidirectional iterator has all the functionality of the forward iterator, and in addition it can be moved backward one location at a time using <strong>operator--</strong>.</p></section><section><title><p>Random-access: like a pointer</p></title><p>Finally, the random-access iterator has all the functionality of the bidirectional iterator plus all the functionality of a pointer (a pointer <emphasis>is</emphasis> a random-access iterator), except that there is no "null" iterator analogue to a null pointer. Basically, anything you can do with a pointer you can do with a random-access iterator, including indexing with <strong>operator[ ]</strong>, adding integral values to a pointer to move it forward or backward by a number of locations, and comparing one iterator to another with <strong>&lt;</strong>, <strong>&gt;=</strong>, and so on.</p></section><section><title><p>Is this really important?</p></title><p>Why do you care about this categorization? When you’re just using containers in a straightforward way (for example, just hand-coding all the operations you want to perform on the objects in the container), it usually doesn’t impact you too much. Things either work or they don’t. The iterator categories become important when:</p><p>3.You use some of the fancier built-in iterator types that will be demonstrated shortly. Or you graduate to creating your own iterators (this will also be demonstrated later in this chapter).</p><p>4.You use the STL algorithms (the subject of the previous chapter). Each of the algorithms has requirements that it places on the iterators with which it works. Knowledge of the iterator categories is even more important when you create your own reusable algorithm templates, because the iterator category that your algorithm requires determines how flexible the algorithm will be. If you require only the most primitive iterator category (input or output), your algorithm will work with <emphasis>everything</emphasis> (<strong>copy( )</strong> is an example of this).</p><p>A hierarchy of iterator tag classes identify the category of an iterator. The class names correspond to the iterator categories, as you would expect, and their derivation reflects the relationship between them:</p><p>struct input_iterator_tag {};</p><p>struct output_iterator_tag {};</p><p>struct forward_iterator_tag: public input_iterator_tag {};</p><p>struct bidirectional_iterator_tag : public</p><p>  forward_iterator_tag {};</p><p>struct random_access_iterator_tag : public</p><p>  bidirectional_iterator_tag {};</p><empty-line/><p>The class <strong>forward_iterator_tag</strong> derives only from <strong>input_iterator_tag</strong>, not from <strong>output_iterator_tag</strong>, because we need to have past-the-end iterator values in algorithms that use forward iterators, but algorithms that use output iterators always assume that <strong>operator*</strong> can be dereferenced. For this reason, it is important to make sure that a past-the-end value is never passed to an algorithm that expects an output iterator.</p><p>For efficiency, certain algorithms provide different implementations for different iterator types, which they infer from the iterator tag defined by the iterator. We will use some of these tag classes later in this chapter when we define our own iterator types<sup>.</sup></p></section></section></section><section><title><p>Predefined iterators</p></title><section><p>The STL has a predefined set of iterators that can be quite handy. For example, you’ve already seen the <strong>reverse_iterator</strong> objects produced by calling <strong>rbegin( )</strong> and <strong>rend( )</strong> for all the basic containers.</p><p>The <emphasis>insertion iterators</emphasis> are necessary because some of the STL algorithms—<strong>copy( ),</strong> for example—use the assignment <strong>operator=</strong> to place objects in the destination container. This is a problem when you’re using the algorithm to <emphasis>fill</emphasis> the container rather than to overwrite items that are already in the destination container—that is, when the space isn’t already there. What the insert iterators do is change the implementation of <strong>operator=</strong> so that instead of doing an assignment, it calls a "push" or "insert" function for that container, thus causing it to allocate new space. The constructors for both <strong>back_insert_iterator</strong> and <strong>front_insert_iterator</strong> take a basic sequence container object (<strong>vector</strong>, <strong>deque</strong> or <strong>list</strong>) as their argument and produce an iterator that calls <strong>push_back( )</strong> or <strong>push_front( )</strong>, respectively, to perform assignment. The helper functions <strong>back_inserter( )</strong> and <strong>front_inserter( )</strong> produce the same objects with a little less typing. Since all the basic sequence containers support <strong>push_back( )</strong>, you will probably find yourself using <strong>back_inserter( )</strong> with some regularity.</p><p>An <strong>insert_iterator</strong> lets you insert elements in the middle of the sequence, again replacing the meaning of <strong>operator=</strong>, but this time by automatically calling <strong>insert( )</strong> instead of one of the "push" functions. The <strong>insert( )</strong> member function requires an iterator indicating the place to insert before, so the <strong>insert_iterator</strong> requires this iterator in addition to the container object. The shorthand function <strong>inserter( )</strong> produces the same object.</p><p>The following example shows the use of the different types of inserters:</p><p>//: C07:Inserters.cpp</p><p>// Different types of iterator inserters</p><p>#include &lt;iostream&gt;</p><p>#include &lt;vector&gt;</p><p>#include &lt;deque&gt;</p><p>#include &lt;list&gt;</p><p>#include &lt;iterator&gt;</p><p>using namespace std;</p><empty-line/><p>int a[] = { 1, 3, 5, 7, 11, 13, 17, 19, 23 };</p><empty-line/><p>template&lt;class Cont&gt;</p><p>void frontInsertion(Cont&amp; ci) {</p><p>  copy(a, a + sizeof(a)/sizeof(Cont::value_type),</p><p>    front_inserter(ci));</p><p>  copy(ci.begin(), ci.end(),</p><p>    ostream_iterator&lt;typename Cont::value_type&gt;(</p><p>    cout, " "));</p><p>  cout &lt;&lt; endl;</p><p>}</p><empty-line/><p>template&lt;class Cont&gt;</p><p>void backInsertion(Cont&amp; ci) {</p><p>  copy(a, a + sizeof(a)/sizeof(Cont::value_type),</p><p>    back_inserter(ci));</p><p>  copy(ci.begin(), ci.end(),</p><p>    ostream_iterator&lt;typename Cont::value_type&gt;(</p><p>    cout, " "));</p><p>  cout &lt;&lt; endl;</p><p>}</p><empty-line/><p>template&lt;class Cont&gt;</p><p>void midInsertion(Cont&amp; ci) {</p><p>  typename Cont::iterator it = ci.begin();</p><p>  it++; it++; it++;</p><p>  copy(a, a + sizeof(a)/(sizeof(Cont::value_type) * 2),</p><p>    inserter(ci, it));</p><p>  copy(ci.begin(), ci.end(),</p><p>    ostream_iterator&lt;typename Cont::value_type&gt;(</p><p>    cout, " "));</p><p>  cout &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main() {</p><p>  deque&lt;int&gt; di;</p><p>  list&lt;int&gt;  li;</p><p>  vector&lt;int&gt; vi;</p><p>  // Can't use a front_inserter() with vector</p><p>  frontInsertion(di);</p><p>  frontInsertion(li);</p><p>  di.clear();</p><p>  li.clear();</p><p>  backInsertion(vi);</p><p>  backInsertion(di);</p><p>  backInsertion(li);</p><p>  midInsertion(vi);</p><p>  midInsertion(di);</p><p>  midInsertion(li);</p><p>} ///:~</p><empty-line/><p>Since <strong>vector</strong> does not support <strong>push_front( )</strong>, it cannot produce a <strong>front_insertion_iterator</strong>. However, you can see that <strong>vector</strong> does support the other two types of insertions (even though, as you shall see later, <strong>insert( )</strong> is not an efficient operation for <strong>vector</strong>). Note the use of the nested type <strong>Cont::value_type</strong> instead of hard-coding <strong>int</strong>.</p></section><section><section><title><p>More on stream iterators</p></title><p>We introduced the use of the stream iterators <strong>ostream_iterator</strong> (an output iterator) and <strong>istream_iterator</strong> (an input iterator) in conjunction with <strong>copy( )</strong> in the previous chapter. Remember that an output stream doesn’t have any concept of an "end," since you can always just keep writing more elements. However, an input stream eventually terminates (for example, when you reach the end of a file), so you need a way to represent that. An <strong>istream_iterator</strong> has two constructors, one that takes an <strong>istream</strong> and produces the iterator you actually read from, and the other which is the default constructor and produces an object that is the past-the-end sentinel. In the following program this object is named <strong>end</strong>:</p><p>//: C07:StreamIt.cpp</p><p>// Iterators for istreams and ostreams</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  ifstream in("StreamIt.cpp");</p><p>  assure(in, "StreamIt.cpp");</p><p>  istream_iterator&lt;string&gt; begin(in), end;</p><p>  ostream_iterator&lt;string&gt; out(cout, "\n");</p><p>  vector&lt;string&gt; vs;</p><p>  copy(begin, end, back_inserter(vs));</p><p>  copy(vs.begin(), vs.end(), out);</p><p>  *out++ = vs[0];</p><p>  *out++ = "That's all, folks!";</p><p>} ///:~</p><empty-line/><p>When <strong>in</strong> runs out of input (in this case when the end of the file is reached), <strong>init</strong> becomes equivalent to <strong>end,</strong> and the <strong>copy( )</strong> terminates.</p><p>Because <strong>out</strong> is an <strong>ostream_iterator&lt;string&gt;</strong>, you can simply assign any <strong>string</strong> object to the dereferenced iterator using <strong>operator=,</strong> and that <strong>string</strong> will be placed on the output stream, as seen in the two assignments to <strong>out</strong>. Because <strong>out</strong> is defined with a newline as its second argument, these assignments also insert a newline along with each assignment.</p><p>Although it is possible to create an <strong>istream_iterator&lt;char&gt;</strong> and <strong>ostream_iterator&lt;char&gt;</strong>, these actually <emphasis>parse </emphasis>the input and thus will, for example, automatically eat whitespace (spaces, tabs, and newlines), which is not desirable if you want to manipulate an exact representation of an <strong>istream</strong>. Instead, you can use the special iterators <strong>istreambuf_iterator</strong> and <strong>ostreambuf_iterator</strong>, which are designed strictly to move characters<a l:href="#n94" type="note">[94]</a>. Although these are templates, they are meant to be used with template arguments of either <strong>char</strong> or <strong>wchar_t</strong>.<a l:href="#n95" type="note">[95]</a> The following example lets you compare the behavior of the stream iterators with the streambuf iterators:<sup>.</sup></p><p>//: C07:StreambufIterator.cpp</p><p>// istreambuf_iterator &amp; ostreambuf_iterator</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  ifstream in("StreambufIterator.cpp");</p><p>  assure(in, "StreambufIterator.cpp");</p><p>  // Exact representation of stream:</p><p>  istreambuf_iterator&lt;char&gt; isb(in), end;</p><p>  ostreambuf_iterator&lt;char&gt; osb(cout);</p><p>  while(isb != end)</p><p>    *osb++ = *isb++; // Copy 'in' to cout</p><p>  cout &lt;&lt; endl;</p><p>  ifstream in2("StreambufIterator.cpp");</p><p>  // Strips white space:</p><p>  istream_iterator&lt;char&gt; is(in2), end2;</p><p>  ostream_iterator&lt;char&gt; os(cout);</p><p>  while(is != end2)</p><p>    *os++ = *is++;</p><p>  cout &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The stream iterators use the parsing defined by <strong>istream::operator&gt;&gt;</strong>, which is probably not what you want if you are parsing characters directly—it’s fairly rare that you want all the whitespace stripped out of your character stream. You’ll virtually always want to use a streambuf iterator when using characters and streams, rather than a stream iterator. In addition, <strong>istream::operator&gt;&gt;</strong> adds significant overhead for each operation, so it is only appropriate for higher-level operations such as parsing numbers.<a l:href="#n96" type="note">[96]</a></p></section><section><title><p>Manipulating raw storage</p></title><p>The <strong>raw_storage_iterator</strong> is defined in <strong>&lt;memory&gt;</strong> and is an output iterator. It is provided to enable algorithms to store their results in uninitialized memory. The interface is quite simple: the constructor takes an output iterator that is pointing to the raw memory (thus it is typically a pointer), and the <strong>operator=</strong> assigns an object into that raw memory. The template parameters are the type of the output iterator pointing to the raw storage and the type of object that will be stored. Here’s an example that creates <strong>Noisy</strong> objects, which print trace statements for their construction, assignment, and destruction (we’ll show the class definition later):</p><p>//: C07:RawStorageIterator.cpp</p><p>// Demonstrate the raw_storage_iterator</p><p>//{-bor}</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;algorithm&gt;</p><p>#include "Noisy.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  const int quantity = 10;</p><p>  // Create raw storage and cast to desired type:</p><p>  Noisy* np =</p><p>    reinterpret_cast&lt;Noisy*&gt;(</p><p>      new char[quantity * sizeof(Noisy)]);</p><p>  raw_storage_iterator&lt;Noisy*, Noisy&gt; rsi(np);</p><p>  for(int i = 0; i &lt; quantity; i++)</p><p>    *rsi++ = Noisy(); // Place objects in storage</p><p>  cout &lt;&lt; endl;</p><p>  copy(np, np + quantity,</p><p>    ostream_iterator&lt;Noisy&gt;(cout, " "));</p><p>  cout &lt;&lt; endl;</p><p>  // Explicit destructor call for cleanup:</p><p>  for(int j = 0; j &lt; quantity; j++)</p><p>    (&amp;np[j])-&gt;~Noisy();</p><p>  // Release raw storage:</p><p>  delete reinterpret_cast&lt;char*&gt;(np);</p><p>} ///:~</p><empty-line/><p>To make the <strong>raw_storage_iterator </strong>template happy, the raw storage must be of the same type as the objects you’re creating. That’s why the pointer from the new array of <strong>char</strong> is cast to a <strong>Noisy*</strong>. The assignment operator forces the objects into the raw storage using the copy-constructor. Note that the explicit destructor call must be made for proper cleanup, and this also allows the objects to be deleted one at a time during container manipulation. In addition, the expression <strong>delete np;</strong> would be invalid anyway since the static type of a pointer in a <strong>delete</strong> expression must be the same as the type assigned to in the <strong>new</strong> expression<sup>.</sup></p></section></section></section></section><section><title><p>The basic sequences: vector, list, deque</p></title><section><p>Sequences keep objects in whatever order you store them. They differ in the efficiency of their operations, however, so if you are going to manipulate a sequence in a particular fashion, choose the appropriate container for those types of manipulations. So far in this book we’ve been using <strong>vector</strong> as the container of choice. This is quite often the case in applications. However, when you start making more sophisticated uses of containers, it becomes important to know more about their underlying implementations and behavior so that you can make the right choices.</p></section><section><title><p>Basic sequence operations</p></title><p>Using a template, the following example shows the operations that all the basic sequences, <strong>vector</strong>, <strong>deque,</strong> and <strong>list</strong>, support<sup>.</sup></p><p>//: C07:BasicSequenceOperations.cpp</p><p>// The operations available for all the</p><p>// basic sequence Containers.</p><p>#include &lt;deque&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;list&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;typename Container&gt;</p><p>void print(Container&amp; c, char* title = "") {</p><p>  cout &lt;&lt; title &lt;&lt; ':' &lt;&lt; endl;</p><p>  if(c.empty()) {</p><p>    cout &lt;&lt; "(empty)" &lt;&lt; endl;</p><p>    return;</p><p>  }</p><p>  typename Container::iterator it;</p><p>  for(it = c.begin(); it != c.end(); it++)</p><p>    cout &lt;&lt; *it &lt;&lt; " ";</p><p>  cout &lt;&lt; endl;</p><p>  cout &lt;&lt; "size() " &lt;&lt; c.size()</p><p>    &lt;&lt; " max_size() "&lt;&lt; c.max_size()</p><p>    &lt;&lt; " front() " &lt;&lt; c.front()</p><p>    &lt;&lt; " back() " &lt;&lt; c.back() &lt;&lt; endl;</p><p>}</p><empty-line/><p>template&lt;typename ContainerOfInt&gt;</p><p>void basicOps(char* s) {</p><p>  cout &lt;&lt; "------- " &lt;&lt; s &lt;&lt; " -------" &lt;&lt; endl;</p><p>  typedef ContainerOfInt Ci;</p><p>  Ci c;</p><p>  print(c, "c after default constructor");</p><p>  Ci c2(10, 1); // 10 elements, values all 1</p><p>  print(c2, "c2 after constructor(10,1)");</p><p>  int ia[] = { 1, 3, 5, 7, 9 };</p><p>  const int iasz = sizeof(ia)/sizeof(*ia);</p><p>  // Initialize with begin &amp; end iterators:</p><p>  Ci c3(ia, ia + iasz);</p><p>  print(c3, "c3 after constructor(iter,iter)");</p><p>  Ci c4(c2); // Copy-constructor</p><p>  print(c4, "c4 after copy-constructor(c2)");</p><p>  c = c2; // Assignment operator</p><p>  print(c, "c after operator=c2");</p><p>  c.assign(10, 2); // 10 elements, values all 2</p><p>  print(c, "c after assign(10, 2)");</p><p>  // Assign with begin &amp; end iterators:</p><p>  c.assign(ia, ia + iasz);</p><p>  print(c, "c after assign(iter, iter)");</p><p>  cout &lt;&lt; "c using reverse iterators:" &lt;&lt; endl;</p><p>  typename Ci::reverse_iterator rit = c.rbegin();</p><p>  while(rit != c.rend())</p><p>    cout &lt;&lt; *rit++ &lt;&lt; " ";</p><p>  cout &lt;&lt; endl;</p><p>  c.resize(4);</p><p>  print(c, "c after resize(4)");</p><p>  c.push_back(47);</p><p>  print(c, "c after push_back(47)");</p><p>  c.pop_back();</p><p>  print(c, "c after pop_back()");</p><p>  typename Ci::iterator it = c.begin();</p><p>  it++; it++;</p><p>  c.insert(it, 74);</p><p>  print(c, "c after insert(it, 74)");</p><p>  it = c.begin();</p><p>  it++;</p><p>  c.insert(it, 3, 96);</p><p>  print(c, "c after insert(it, 3, 96)");</p><p>  it = c.begin();</p><p>  it++;</p><p>  c.insert(it, c3.begin(), c3.end());</p><p>  print(c, "c after insert("</p><p>    "it, c3.begin(), c3.end())");</p><p>  it = c.begin();</p><p>  it++;</p><p>  c.erase(it);</p><p>  print(c, "c after erase(it)");</p><p>  typename Ci::iterator it2 = it = c.begin();</p><p>  it++;</p><p>  it2++; it2++; it2++; it2++; it2++;</p><p>  c.erase(it, it2);</p><p>  print(c, "c after erase(it, it2)");</p><p>  c.swap(c2);</p><p>  print(c, "c after swap(c2)");</p><p>  c.clear();</p><p>  print(c, "c after clear()");</p><p>}</p><empty-line/><p>int main() {</p><p>  basicOps&lt;vector&lt;int&gt; &gt;("vector");</p><p>  basicOps&lt;deque&lt;int&gt; &gt;("deque");</p><p>  basicOps&lt;list&lt;int&gt; &gt;("list");</p><p>} ///:~</p><empty-line/><p>The first function template, <strong>print( )</strong>, demonstrates the basic information you can get from any sequence container: whether it’s empty, its current size, the size of the largest possible container, the element at the beginning, and the element at the end. You can also see that every container has <strong>begin( )</strong> and <strong>end( )</strong> member functions that return iterators.</p><p>The <strong>basicOps( )</strong> function tests everything else (and in turn calls <strong>print( )</strong>), including a variety of constructors: default, copy-constructor, quantity and initial value, and beginning and ending iterators. There are an assignment <strong>operator=</strong> and two kinds of <strong>assign( )</strong> member functions. One takes a quantity and an initial value, and the other takes a beginning and ending iterator.</p><p>All the basic sequence containers are reversible containers, as shown by the use of the <strong>rbegin( )</strong> and <strong>rend( )</strong> member functions. A sequence container can be resized, and the entire contents of the container can be removed with <strong>clear( )</strong>. When you call resize( ) to expand a sequence, the new elements use the default constructor of the type of element in the sequence, or if they are built-in types, they are zero-initialized<sup>.</sup></p><p>Using an iterator to indicate where you want to start inserting into any sequence container, you can <strong>insert( )</strong> a single element, a number of elements that all have the same value, and a group of elements from another container using the beginning and ending iterators of that group<sup>.</sup></p><p>To <strong>erase( )</strong> a single element from the middle, use an iterator; to <strong>erase( )</strong> a range of elements, use a pair of iterators. Notice that since a <strong>list</strong> supports only bidirectional iterators, all the iterator motion must be performed with increments and decrements. (If the containers were limited to <strong>vector </strong>and <strong>deque</strong>, which produce random-access iterators, <strong>operator+</strong> and <strong>operator-</strong> could have been used to move the iterators in big jumps.)</p><p>Although both <strong>list</strong> and <strong>deque</strong> support <strong>push_front( )</strong> and <strong>pop_front( )</strong>, <strong>vector</strong> does not, so the only member functions that work with all three are <strong>push_back( )</strong> and <strong>pop_back( )</strong>.</p><p>The naming of the member function <strong>swap( )</strong> is a little confusing, since there’s also a nonmember <strong>swap( )</strong> algorithm that interchanges the values of any two objects of same type. The member <strong>swap( )</strong> swaps everything in one container for another (if the containers hold the same type), effectively swapping the containers themselves. It does this efficiently by swapping the contents of each container, which consists mostly of just pointers. The nonmember <strong>swap( )</strong> algorithm normally uses assignment to interchange its arguments (an expensive operation for an entire container), but is customized through template specialization to call the member <strong>swap( )</strong> for the standard containers. There is also an <strong>iter_swap</strong> algorithm that interchanges two elements in the same container pointed to by iterators<sup>.</sup></p><p>The following sections discuss the particulars of each type of sequence container.</p></section><section><title><p>vector</p></title><section><p>The <strong>vector</strong> class template is intentionally made to look like a souped-up array, since it has array-style indexing, but also can expand dynamically. The <strong>vector</strong> class template is so fundamentally useful that it was introduced in a primitive way early in this book and was used regularly in previous examples. This section will give a more in-depth look at <strong>vector</strong>.</p><p>To achieve maximally fast indexing and iteration, the <strong>vector</strong> maintains its storage as a single contiguous array of objects. This is a critical point to observe in understanding the behavior of <strong>vector</strong>. It means that indexing and iteration are lightning-fast, being basically the same as indexing and iterating over an array of objects. But it also means that inserting an object anywhere but at the end (that is, appending) is not really an acceptable operation for a <strong>vector</strong>. In addition, when a <strong>vector</strong> runs out of preallocated storage, to maintain its contiguous array it must allocate a whole new (larger) chunk of storage elsewhere and copy the objects to the new storage. This approach produces a number of unpleasant side-effects.</p></section><section><section><title><p>Cost of overflowing allocated storage</p></title><p>A <strong>vector </strong>starts by grabbing a block of storage, as if it’s taking a guess at how many objects you plan to put in it. As long as you don’t try to put in more objects than can be held in the initial block of storage, everything is rapid and efficient. (If you <emphasis>do </emphasis>know how many objects to expect, you can preallocate storage using <strong>reserve( ).</strong>) But eventually you will put in one too many objects, and the <strong>vector </strong>responds by:</p><p>1.Allocating a new, bigger piece of storage</p><p>2.Copying all the objects from the old storage to the new (using the copy-constructor)</p><p>3.Destroying all the old objects (the destructor is called for each one)</p><p>4.Releasing the old memory</p><p>For complex objects, this copy-construction and destruction can end up being expensive if you overfill your vector a lot, which is why vectors (and STL containers in general) are designed for value types (i.e. types that are cheap to copy). Of course, that includes pointers.</p><p>To see what happens when you’re filling a <strong>vector</strong>, here is the <strong>Noisy</strong> class mentioned earlier that prints information about its creations, destructions, assignments, and copy-constructions:</p><p>//: C07:Noisy.h</p><p>// A class to track various object activities</p><p>#ifndef NOISY_H</p><p>#define NOISY_H</p><p>#include &lt;iostream&gt;</p><p>using std::endl;</p><empty-line/><p>class Noisy {</p><p>  static long create, assign, copycons, destroy;</p><p>  long id;</p><p>public:</p><p>  Noisy() : id(create++) {</p><p>    std::cout &lt;&lt; "d[" &lt;&lt; id &lt;&lt; "]" &lt;&lt; std::endl;</p><p>  }</p><p>  Noisy(const Noisy&amp; rv) : id(rv.id) {</p><p>    std::cout &lt;&lt; "c[" &lt;&lt; id &lt;&lt; "]" &lt;&lt; std::endl;</p><p>    copycons++;</p><p>  }</p><p>  Noisy&amp; operator=(const Noisy&amp; rv) {</p><p>    std::cout &lt;&lt; "(" &lt;&lt; id &lt;&lt; ")=[" &lt;&lt;</p><p>      rv.id &lt;&lt; "]" &lt;&lt; std::endl;</p><p>    id = rv.id;</p><p>    assign++;</p><p>    return *this;</p><p>  }</p><p>  friend bool</p><p>  operator&lt;(const Noisy&amp; lv, const Noisy&amp; rv) {</p><p>    return lv.id &lt; rv.id;</p><p>  }</p><p>  friend bool</p><p>  operator==(const Noisy&amp; lv, const Noisy&amp; rv) {</p><p>    return lv.id == rv.id;</p><p>  }</p><p>  ~Noisy() {</p><p>    std::cout &lt;&lt; "~[" &lt;&lt; id &lt;&lt; "]" &lt;&lt; std::endl;</p><p>    destroy++;</p><p>  }</p><p>  friend std::ostream&amp;</p><p>  operator&lt;&lt;(std::ostream&amp; os, const Noisy&amp; n) {</p><p>    return os &lt;&lt; n.id;</p><p>  }</p><p>  friend class NoisyReport;</p><p>};</p><empty-line/><p>struct NoisyGen {</p><p>  Noisy operator()() { return Noisy(); }</p><p>};</p><empty-line/><p>// A Singleton. Will automatically report the</p><p>// statistics as the program terminates:</p><p>class NoisyReport {</p><p>  static NoisyReport nr;</p><p>  NoisyReport() {} // Private constructor</p><p>public:</p><p>  ~NoisyReport() {</p><p>    std::cout &lt;&lt; "\n-------------------\n"</p><p>      &lt;&lt; "Noisy creations: " &lt;&lt; Noisy::create</p><p>      &lt;&lt; "\nCopy-Constructions: "</p><p>      &lt;&lt; Noisy::copycons</p><p>      &lt;&lt; "\nAssignments: " &lt;&lt; Noisy::assign</p><p>      &lt;&lt; "\nDestructions: " &lt;&lt; Noisy::destroy</p><p>      &lt;&lt; std::endl;</p><p>  }</p><p>};</p><empty-line/><p>// Because of the following definitions, this file</p><p>// can only be used in simple test situations. Move</p><p>// them to a .cpp file for more complex programs:</p><p>long Noisy::create = 0, Noisy::assign = 0,</p><p>  Noisy::copycons = 0, Noisy::destroy = 0;</p><p>NoisyReport NoisyReport::nr;</p><p>#endif // NOISY_H ///:~</p><empty-line/><p>Each <strong>Noisy</strong> object has its own identifier, and <strong>static</strong> variables keep track of all the creations, assignments (using <strong>operator=</strong>), copy-constructions, and destructions. The <strong>id</strong> is initialized using the <strong>create</strong> counter inside the default constructor; the copy-constructor and assignment operator take their <strong>id</strong> values from the rvalue. Of course, with <strong>operator=</strong> the lvalue is already an initialized object, so the old value of <strong>id</strong> is printed before it is overwritten with the <strong>id</strong> from the rvalue.</p><p>To support certain operations such as sorting and searching (which are used implicitly by some of the containers), <strong>Noisy</strong> must have an <strong>operator&lt;</strong> and <strong>operator==</strong>. These simply compare the <strong>id</strong> values. The <strong>ostream</strong> inserter follows the standard form and simply prints the <strong>id</strong>.</p><p>Objects of type <strong>NoisyGen</strong> are function objects (since there is an <strong>operator( )</strong>) that produce <strong>Noisy</strong> objects during testing<sup>.</sup></p><p><strong>NoisyReport</strong> is a Singleton object, because we only want one report printed at program termination. It has a <strong>private</strong> constructor, therefore, so no additional <strong>NoisyReport</strong> objects can be created, and it has a single static instance of <strong>NoisyReport</strong> called <strong>nr</strong>. The only executable statements are in the destructor, which is called as the program exits and the static destructors are called; this destructor prints the statistics captured by the <strong>static</strong> variables in <strong>Noisy</strong>.</p><p>The one snag to this header file is the inclusion of the definitions for the <strong>static</strong>s at the end. If you include this header in more than one place in your project, you’ll get multiple-definition errors at link time. Of course, you can put the <strong>static</strong> definitions in a separate <strong>cpp</strong> file and link it in, but that is less convenient, and since <strong>Noisy</strong> is just intended for quick-and-dirty experiments, the header file should be reasonable for most situations.</p><p>Using <strong>Noisy.h</strong>, the following program will show the behaviors that occur when a <strong>vector</strong> overflows its currently allocated storage:</p><p>//: C07:VectorOverflow.cpp</p><p>//{-bor}</p><p>// Shows the copy-construction and destruction</p><p>// That occurs when a vector must reallocate</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "Noisy.h"</p><p>using namespace std;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  int size = 1000;</p><p>  if(argc &gt;= 2) size = atoi(argv[1]);</p><p>  vector&lt;Noisy&gt; vn;</p><p>  Noisy n;</p><p>  for(int i = 0; i &lt; size; i++)</p><p>    vn.push_back(n);</p><p>  cout &lt;&lt; "\n cleaning up \n";</p><p>} ///:~</p><empty-line/><p>You can use the default value of 1000, or you can use your own value by putting it on the command line.</p><p>When you run this program, you’ll see a single default constructor call (for <strong>n</strong>), then a lot of copy-constructor calls, then some destructor calls, then some more copy-constructor calls, and so on. When the vector runs out of space in the linear array of bytes it has allocated, it must (to maintain all the objects in a linear array, which is an essential part of its job) get a bigger piece of storage and move everything over, copying first and then destroying the old objects. You can imagine that if you store a lot of large and complex objects, this process could rapidly become prohibitive.</p><p>There are two solutions to this problem. The nicest one requires that you know beforehand how many objects you’re going to make. In that case, you can use <strong>reserve( )</strong> to tell the vector how much storage to preallocate, thus eliminating all the copies and destructions and making everything very fast (especially random access to the objects with <strong>operator[ ]</strong>). Note that the use of <strong>reserve( )</strong> is different from using the <strong>vector</strong> constructor with an integral first argument; the latter initializes each element using the default copy-constructor.</p><p>However, in the more general case you won’t know how many objects you’ll need. If <strong>vector</strong> reallocations are slowing things down, you can change sequence containers. You could use a <strong>list</strong>, but as you’ll see, the <strong>deque</strong> allows speedy insertions at either end of the sequence and never needs to copy or destroy objects as it expands its storage. The <strong>deque</strong> also allows random access with <strong>operator[ ]</strong>, but it’s not quite as fast as <strong>vector</strong>’s <strong>operator[ ]</strong>. So if you’re creating all your objects in one part of the program and randomly accessing them in another, you may find yourself filling a <strong>deque</strong> and then creating a <strong>vector</strong> from the <strong>deque</strong> and using the <strong>vector</strong> for rapid indexing. Of course, you don’t want to program this way habitually; just be aware of these issues (avoid premature optimization).</p><p>There is a darker side to <strong>vector</strong>’s reallocation of memory, however. Because <strong>vector</strong> keeps its objects in a nice, neat array (allowing, for one thing, maximally fast random access), the iterators used by <strong>vector</strong> can be simple pointers. This is a good thing—of all the sequence containers, these pointers allow the fastest selection and manipulation. Whether they are simple pointers, or whether they are iterator objects that hold an internal pointer into their container, consider what happens when you add the one additional object that causes the <strong>vector</strong> to reallocate storage and move it elsewhere. The iterator’s pointer is now pointing off into nowhere:<sup>.</sup></p><p>//: C07:VectorCoreDump.cpp</p><p>// Invalidating an iterator</p><p>#include &lt;iterator&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  vector&lt;int&gt; vi(10, 0);</p><p>  ostream_iterator&lt;int&gt; out(cout, " ");</p><p>  vector&lt;int&gt;::iterator i = vi.begin();</p><p>  *i = 47;</p><p>  copy(vi.begin(), vi.end(), out);</p><p>  cout &lt;&lt; endl;</p><p>  // Force it to move memory (could also just add</p><p>  // enough objects):</p><p>  vi.resize(vi.capacity() + 1);</p><p>  // Now i points to wrong memory:</p><p>  *i = 48;  // Access violation</p><p>  copy(vi.begin(), vi.end(), out); // No change to vi[0]</p><p>} ///:~</p><empty-line/><p>This illustrates the concept of <emphasis>iterator invalidation</emphasis>. Certain operations cause internal changes to a container’s underlying data, so any iterators in effect before such changes may no longer be valid afterward. If your program is breaking mysteriously, look for places where you hold onto an iterator while adding more objects to a <strong>vector</strong>. You’ll need to get a new iterator after adding elements or use <strong>operator[ ] </strong>instead for element selections. If you combine this observation with the awareness of the potential expense for adding new objects to a <strong>vector</strong>, you may conclude that the safest way to use one is to fill it up all at once (ideally, knowing first how many objects you’ll need) and then just use it (without adding more objects) elsewhere in the program. This is the way <strong>vector</strong> has been used in the book up to this point. The standard C++ library documents which container operations invalidate iterators.</p><p>You may observe that using <strong>vector </strong>as the "basic" container in the earlier chapters of this book might not be the best choice in all cases. This is a fundamental issue in containers and in data structures in general: the "best" choice varies according to the way the container is used. The reason <strong>vector</strong> has been the "best" choice up until now is that it looks a lot like an array and was thus familiar and easy for you to adopt. But from now on it’s also worth thinking about other issues when choosing containers.</p></section><section><title><p>Inserting and erasing elements</p></title><p>The <strong>vector</strong> is most efficient if:</p><p>5.You <strong>reserve( )</strong> the correct amount of storage at the beginning so the <strong>vector</strong> never has to reallocate.</p><p>6.You only add and remove elements from the back end.</p><p>It is possible to insert and erase elements from the middle of a <strong>vector</strong> using an iterator, but the following program demonstrates what a bad idea this is:</p><p>//: C07:VectorInsertAndErase.cpp</p><p>// Erasing an element from a vector</p><p>//{-bor}</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;vector&gt;</p><p>#include "Noisy.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  vector&lt;Noisy&gt; v;</p><p>  v.reserve(11);</p><p>  cout &lt;&lt; "11 spaces have been reserved" &lt;&lt; endl;</p><p>  generate_n(back_inserter(v), 10, NoisyGen());</p><p>  ostream_iterator&lt;Noisy&gt; out(cout, " ");</p><p>  cout &lt;&lt; endl;</p><p>  copy(v.begin(), v.end(), out);</p><p>  cout &lt;&lt; "Inserting an element:" &lt;&lt; endl;</p><p>  vector&lt;Noisy&gt;::iterator it =</p><p>    v.begin() + v.size() / 2; // Middle</p><p>  v.insert(it, Noisy());</p><p>  cout &lt;&lt; endl;</p><p>  copy(v.begin(), v.end(), out);</p><p>  cout &lt;&lt; "\nErasing an element:" &lt;&lt; endl;</p><p>  // Cannot use the previous value of it:</p><p>  it = v.begin() + v.size() / 2;</p><p>  v.erase(it);</p><p>  cout &lt;&lt; endl;</p><p>  copy(v.begin(), v.end(), out);</p><p>  cout &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>When you run the program, you’ll see that the call to <strong>reserve( )</strong> really does only allocate storage—no constructors are called. The <strong>generate_n( )</strong> call is busy: each call to <strong>NoisyGen::operator( )</strong> results in a construction, a copy-construction (into the <strong>vector</strong>), and a destruction of the temporary. But when an object is inserted into the <strong>vector</strong> in the middle, it must shove everything down to maintain the linear array, and, since there is enough space, it does this with the assignment operator. (If the argument of <strong>reserve( )</strong> is 10 instead of 11, it would have to reallocate storage.) When an object is erased from the <strong>vector</strong>, the assignment operator is once again used to move everything up to cover the place that is being erased. (Notice that this requires that the assignment operator properly clean up the lvalue.) Last, the object on the end of the array is deleted.</p></section></section></section><section><title><p>deque</p></title><p>The <strong>deque</strong> container is a basic sequence optimized for adding and removing elements from either end. It also allows for reasonably fast random access—it has an <strong>operator[ ]</strong> like <strong>vector</strong>. However, it does not have <strong>vector</strong>’s constraint of keeping everything in a single sequential block of memory. Instead, a typical implementation of <strong>deque</strong> uses multiple blocks of sequential storage (keeping track of all the blocks and their order in a mapping structure). For this reason, the overhead for a <strong>deque</strong> to add or remove elements at either end is low. In addition, it never needs to copy and destroy contained objects during a new storage allocation (like <strong>vector</strong> does), so it is far more efficient than <strong>vector</strong> if you are adding an unknown quantity of objects at either end. This means that <strong>vector</strong> is the best choice only if you have a good idea of how many objects you need. In addition, many of the programs shown earlier in this book that use <strong>vector</strong> and <strong>push_back( )</strong> might be more efficient with a <strong>deque</strong>. The interface to <strong>deque</strong> is only slightly different from a <strong>vector</strong> (<strong>deque</strong> has a <strong>push_front( )</strong> and <strong>pop_front( )</strong> while <strong>vector</strong> does not, for example), so converting code from using <strong>vector</strong> to using <strong>deque</strong> is almost trivial. Consider <strong>StringVector.cpp</strong>, which can be changed to use <strong>deque</strong> by replacing the word "vector" with "deque" everywhere. The following program adds parallel <strong>deque</strong> operations to the <strong>vector</strong> operations in <strong>StringVector.cpp</strong> and performs timing comparisons:</p><p>//: C07:StringDeque.cpp</p><p>// Converted from StringVector.cpp</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;deque&gt;</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  char* fname = "StringDeque.cpp";</p><p>  if(argc &gt; 1) fname = argv[1];</p><p>  ifstream in(fname);</p><p>  assure(in, fname);</p><p>  vector&lt;string&gt; vstrings;</p><p>  deque&lt;string&gt; dstrings;</p><p>  string line;</p><p>  // Time reading into vector:</p><p>  clock_t ticks = clock();</p><p>  while(getline(in, line))</p><p>    vstrings.push_back(line);</p><p>  ticks = clock() - ticks;</p><p>  cout &lt;&lt; "Read into vector: " &lt;&lt; ticks &lt;&lt; endl;</p><p>  // Repeat for deque:</p><p>  ifstream in2(fname);</p><p>  assure(in2, fname);</p><p>  ticks = clock();</p><p>  while(getline(in2, line))</p><p>    dstrings.push_back(line);</p><p>  ticks = clock() - ticks;</p><p>  cout &lt;&lt; "Read into deque: " &lt;&lt; ticks &lt;&lt; endl;</p><p>  // Now compare indexing:</p><p>  ticks = clock();</p><p>  for(size_t i = 0; i &lt; vstrings.size(); i++) {</p><p>    ostringstream ss;</p><p>    ss &lt;&lt; i;</p><p>    vstrings[i] = ss.str() + ": " + vstrings[i];</p><p>  }</p><p>  ticks = clock() - ticks;</p><p>  cout &lt;&lt; "Indexing vector: " &lt;&lt; ticks &lt;&lt; endl;</p><p>  ticks = clock();</p><p>  for(size_t j = 0; j &lt; dstrings.size(); j++) {</p><p>    ostringstream ss;</p><p>    ss &lt;&lt; j;</p><p>    dstrings[j] = ss.str() + ": " + dstrings[j];</p><p>  }</p><p>  ticks = clock() - ticks;</p><p>  cout &lt;&lt; "Indexing deque: " &lt;&lt; ticks &lt;&lt; endl;</p><p>  // Compare iteration</p><p>  ofstream tmp1("tmp1.tmp"), tmp2("tmp2.tmp");</p><p>  ticks = clock();</p><p>  copy(vstrings.begin(), vstrings.end(),</p><p>    ostream_iterator&lt;string&gt;(tmp1, "\n"));</p><p>  ticks = clock() - ticks;</p><p>  cout &lt;&lt; "Iterating vector: " &lt;&lt; ticks &lt;&lt; endl;</p><p>  ticks = clock();</p><p>  copy(dstrings.begin(), dstrings.end(),</p><p>    ostream_iterator&lt;string&gt;(tmp2, "\n"));</p><p>  ticks = clock() - ticks;</p><p>  cout &lt;&lt; "Iterating deque: " &lt;&lt; ticks &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>Knowing now what you do about the inefficiency of adding things to <strong>vector</strong> because of storage reallocation, you might expect dramatic differences between the two. However, on a 1.7MB text file, one compiler’s program produced the following (measured in platform/compiler specific clock ticks, not seconds):</p><p>Read into vector: 8350</p><p>Read into deque: 7690</p><p>Indexing vector: 2360</p><p>Indexing deque: 2480</p><p>Iterating vector: 2470</p><p>Iterating deque: 2410</p><empty-line/><p>A different compiler and platform roughly agreed with this. It’s not so dramatic, is it? This points out some important issues:</p><p>1.We (programmers and authors) are typically bad at guessing where inefficiencies occur in our programs.</p><p>2.Efficiency comes from a combination of effects. Here, reading the lines in and converting them to strings may dominate over the cost of the <strong>vector</strong> vs. <strong>deque</strong>.</p><p>3.The <strong>string</strong> class is probably fairly well designed in terms of efficiency.</p><p>Of course, this doesn’t mean you shouldn’t use a <strong>deque</strong> rather than a <strong>vector</strong> when you know that an uncertain number of objects will be pushed onto the end of the container. On the contrary, you should—when you’re tuning for performance. But also be aware that performance issues are usually not where you think they are, and the only way to know for sure where your bottlenecks are is by testing. Later in this chapter, you’ll see a more "pure" comparison of performance between <strong>vector</strong>, <strong>deque,</strong> and <strong>list</strong>.</p></section><section><title><p>Converting between sequences</p></title><section><p>Sometimes you need the behavior or efficiency of one kind of container for one part of your program, and you need a different container’s behavior or efficiency in another part of the program. For example, you may need the efficiency of a <strong>deque</strong> when adding objects to the container but the efficiency of a <strong>vector</strong> when indexing them. Each of the basic sequence containers (<strong>vector</strong>, <strong>deque,</strong> and <strong>list</strong>) has a two-iterator constructor (indicating the beginning and ending of the sequence to read from when creating a new object) and an <strong>assign( )</strong> member function to read into an existing container, so you can easily move objects from one sequence container to another.</p><p>The following example reads objects into a <strong>deque</strong> and then converts to a <strong>vector</strong>:</p><p>//: C07:DequeConversion.cpp</p><p>// Reading into a Deque, converting to a vector</p><p>//{-bor}</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;deque&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;vector&gt;</p><p>#include "Noisy.h"</p><p>using namespace std;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  int size = 25;</p><p>  if(argc &gt;= 2) size = atoi(argv[1]);</p><p>  deque&lt;Noisy&gt; d;</p><p>  generate_n(back_inserter(d), size, NoisyGen());</p><p>  cout &lt;&lt; "\n Converting to a vector(1)" &lt;&lt; endl;</p><p>  vector&lt;Noisy&gt; v1(d.begin(), d.end());</p><p>  cout &lt;&lt; "\n Converting to a vector(2)" &lt;&lt; endl;</p><p>  vector&lt;Noisy&gt; v2;</p><p>  v2.reserve(d.size());</p><p>  v2.assign(d.begin(), d.end());</p><p>  cout &lt;&lt; "\n Cleanup" &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>You can try various sizes, but note that it makes no difference—the objects are simply copy-constructed into the new <strong>vector</strong>s. What’s interesting is that <strong>v1</strong> does not cause multiple allocations while building the <strong>vector</strong>, no matter how many elements you use. You might initially think that you must follow the process used for <strong>v2</strong> and preallocate the storage to prevent messy reallocations, but this is unnecessary because the constructor used for <strong>v1</strong> determines the memory need ahead of time.</p></section><section><section><title><p>Cost of overflowing allocated storage</p></title><p>It’s illuminating to see what happens with a <strong>deque</strong> when it overflows a block of storage, in contrast with <strong>VectorOverflow.cpp</strong>:</p><p>//: C07:DequeOverflow.cpp</p><p>//{-bor}</p><p>// A deque is much more efficient than a vector</p><p>// when pushing back a lot of elements, since it</p><p>// doesn't require copying and destroying.</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;deque&gt;</p><p>#include "Noisy.h"</p><p>using namespace std;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  int size = 1000;</p><p>  if(argc &gt;= 2) size = atoi(argv[1]);</p><p>  deque&lt;Noisy&gt; dn;</p><p>  Noisy n;</p><p>  for(int i = 0; i &lt; size; i++)</p><p>    dn.push_back(n);</p><p>  cout &lt;&lt; "\n cleaning up \n";</p><p>} ///:~</p><empty-line/><p>Here you will have relatively few (if any) destructors called before the words "cleaning up" appear. Since the <strong>deque</strong> allocates all its storage in blocks instead of a contiguous array like <strong>vector</strong>, it never needs to move existing storage of each of its data blocks. (Thus, no additional copy-constructions and destructions occur.) The <strong>deque</strong> simply allocates a new block. For the same reason, the <strong>deque</strong> can just as efficiently add elements to the <emphasis>beginning</emphasis> of the sequence, since if it runs out of storage, it (again) just allocates a new block for the beginning. (The index block that holds the data blocks together may need to be reallocated, however.) Insertions in the middle of a <strong>deque</strong>, however, could be even messier than for <strong>vector</strong> (but not as costly).</p><p>Because of <strong>deque</strong>’s clever storage management, an existing iterator is not invalidated after you add new things to either end of a deque, as it was demonstrated to do with <strong>vector</strong> (in <strong>VectorCoreDump.cpp</strong>). If you stick to what <strong>deque</strong> is best at—insertions and removals from either end, reasonably rapid traversals and fairly fast random-access using <strong>operator[ ]</strong>—you’ll be in good shape.</p></section></section></section><section><title><p>Checked random-access</p></title><p>Both <strong>vector </strong>and <strong>deque</strong> provide two ways to perform random access of their elements: the <strong>operator[ ]</strong>, which you’ve seen already, and <strong>at( )</strong>, which checks the boundaries of the container that’s being indexed and throws an exception if you go out of bounds. It does cost more to use <strong>at( )</strong>:</p><p>//: C07:IndexingVsAt.cpp</p><p>// Comparing "at()" to operator[]</p><p>#include &lt;ctime&gt;</p><p>#include &lt;deque&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  long count = 1000;</p><p>  int sz = 1000;</p><p>  if(argc &gt;= 2) count = atoi(argv[1]);</p><p>  if(argc &gt;= 3) sz = atoi(argv[2]);</p><p>  vector&lt;int&gt; vi(sz);</p><p>  clock_t ticks = clock();</p><p>  for(int i1 = 0; i1 &lt; count; i1++)</p><p>    for(int j = 0; j &lt; sz; j++)</p><p>      vi[j];</p><p>  cout &lt;&lt; "vector[] " &lt;&lt; clock() - ticks &lt;&lt; endl;</p><p>  ticks = clock();</p><p>  for(int i2 = 0; i2 &lt; count; i2++)</p><p>    for(int j = 0; j &lt; sz; j++)</p><p>      vi.at(j);</p><p>  cout &lt;&lt; "vector::at() " &lt;&lt; clock()-ticks &lt;&lt;endl;</p><p>  deque&lt;int&gt; di(sz);</p><p>  ticks = clock();</p><p>  for(int i3 = 0; i3 &lt; count; i3++)</p><p>    for(int j = 0; j &lt; sz; j++)</p><p>      di[j];</p><p>  cout &lt;&lt; "deque[] " &lt;&lt; clock() - ticks &lt;&lt; endl;</p><p>  ticks = clock();</p><p>  for(int i4 = 0; i4 &lt; count; i4++)</p><p>    for(int j = 0; j &lt; sz; j++)</p><p>      di.at(j);</p><p>  cout &lt;&lt; "deque::at() " &lt;&lt; clock()-ticks &lt;&lt;endl;</p><p>  // Demonstrate at() when you go out of bounds:</p><p>  try {</p><p>    di.at(vi.size() + 1);</p><p>  } catch(...) {</p><p>    cerr &lt;&lt; "Exception thrown" &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>As you saw in Chapter 1, different systems may handle the uncaught exception in different ways, but you’ll know one way or another that something went wrong with the program when using <strong>at( )</strong>, whereas it’s possible to go blundering ahead using <strong>operator[ ]</strong>.</p></section><section><title><p>list</p></title><section><p>A <strong>list</strong> is implemented as a doubly linked list data structure and is thus designed for rapid insertion and removal of elements <emphasis>anywhere</emphasis> in the sequence, whereas for <strong>vector</strong> and <strong>deque </strong>this is a much more costly operation. A list is so slow when randomly accessing elements that it does not have an <strong>operator[ ]</strong>. It’s best used when you’re traversing a sequence, in order, from beginning to end (or vice-versa), rather than choosing elements randomly from the middle. Even then the traversal can be slower than with a <strong>vector</strong>, but if you aren’t doing a lot of traversals, that won’t be your bottleneck.</p><p>Another thing to be aware of with a <strong>list</strong> is the memory overhead of each link, which requires a forward and backward pointer on top of the storage for the actual object. Thus, a <strong>list</strong> is a better choice when you have larger objects that you’ll be inserting and removing from the middle of the <strong>list</strong>.</p><p>It’s better not to use a <strong>list </strong>if you think you might be traversing it a lot, looking for objects, since the amount of time it takes to get from the beginning of the <strong>list</strong>—which is the only place you can start unless you’ve already got an iterator to somewhere you know is closer to your destination—to the object of interest is proportional to the number of objects between the beginning and that object.</p><p>The objects in a <strong>list </strong>never move after they are created; "moving" a list element means changing the links, but never copying or assigning the actual objects. This means that iterators aren't invalidated when items are added to the list as it was demonstrated earlier to be the case <strong>vector</strong>. Here’s an example using the <strong>Noisy</strong> class:</p><p>//: C07:ListStability.cpp</p><p>// Things don't move around in lists</p><p>//{-bor}</p><p>#include "Noisy.h"</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;list&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  list&lt;Noisy&gt; l;</p><p>  ostream_iterator&lt;Noisy&gt; out(cout, " ");</p><p>  generate_n(back_inserter(l), 25, NoisyGen());</p><p>  cout &lt;&lt; "\n Printing the list:" &lt;&lt; endl;</p><p>  copy(l.begin(), l.end(), out);</p><p>  cout &lt;&lt; "\n Reversing the list:" &lt;&lt; endl;</p><p>  l.reverse();</p><p>  copy(l.begin(), l.end(), out);</p><p>  cout &lt;&lt; "\n Sorting the list:" &lt;&lt; endl;</p><p>  l.sort();</p><p>  copy(l.begin(), l.end(), out);</p><p>  cout &lt;&lt; "\n Swapping two elements:" &lt;&lt; endl;</p><p>  list&lt;Noisy&gt;::iterator it1, it2;</p><p>  it1 = it2 = l.begin();</p><p>  it2++;</p><p>  swap(*it1, *it2);</p><p>  cout &lt;&lt; endl;</p><p>  copy(l.begin(), l.end(), out);</p><p>  cout &lt;&lt; "\n Using generic reverse(): " &lt;&lt; endl;</p><p>  reverse(l.begin(), l.end());</p><p>  cout &lt;&lt; endl;</p><p>  copy(l.begin(), l.end(), out);</p><p>  cout &lt;&lt; "\n Cleanup" &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>Operations as seemingly radical as reversing and sorting the list require no copying of objects, because instead of moving the objects, the links are simply changed. However, notice that <strong>sort( )</strong> and <strong>reverse( )</strong> are member functions of <strong>list</strong>, so they have special knowledge of the internals of <strong>list</strong> and can rearrange the elements instead of copying them. On the other hand, the <strong>swap( )</strong> function is a generic algorithm and doesn’t know about <strong>list</strong> in particular, so it uses the copying approach for swapping two elements. In general, use the member version of an algorithm if that is supplied instead of its generic algorithm equivalent. In particular, use the generic <strong>sort( )</strong> and <strong>reverse( )</strong> algorithms only with arrays, <strong>vector</strong>s, and <strong>deque</strong>s.</p><p>If you have large, complex objects, you might want to choose a <strong>list</strong> first, especially if construction, destruction, copy-construction, and assignment are expensive and if you are doing things like sorting the objects or otherwise reordering them a lot.</p></section><section><section><title><p>Special list operations</p></title><p>The <strong>list</strong> has some special built-in operations to make the best use of the structure of the <strong>list</strong>. You’ve already seen <strong>reverse( )</strong> and <strong>sort( )</strong>, and here are some of the others in use:</p><p>//: C07:ListSpecialFunctions.cpp</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;list&gt;</p><p>#include "Noisy.h"</p><p>using namespace std;</p><p>ostream_iterator&lt;Noisy&gt; out(cout, " ");</p><empty-line/><p>void print(list&lt;Noisy&gt;&amp; ln, char* comment = "") {</p><p>  cout &lt;&lt; "\n" &lt;&lt; comment &lt;&lt; ":\n";</p><p>  copy(ln.begin(), ln.end(), out);</p><p>  cout &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main() {</p><p>  typedef list&lt;Noisy&gt; LN;</p><p>  LN l1, l2, l3, l4;</p><p>  generate_n(back_inserter(l1), 6, NoisyGen());</p><p>  generate_n(back_inserter(l2), 6, NoisyGen());</p><p>  generate_n(back_inserter(l3), 6, NoisyGen());</p><p>  generate_n(back_inserter(l4), 6, NoisyGen());</p><p>  print(l1, "l1"); print(l2, "l2");</p><p>  print(l3, "l3"); print(l4, "l4");</p><p>  LN::iterator it1 = l1.begin();</p><p>  it1++; it1++; it1++;</p><p>  l1.splice(it1, l2);</p><p>  print(l1, "l1 after splice(it1, l2)");</p><p>  print(l2, "l2 after splice(it1, l2)");</p><p>  LN::iterator it2 = l3.begin();</p><p>  it2++; it2++; it2++;</p><p>  l1.splice(it1, l3, it2);</p><p>  print(l1, "l1 after splice(it1, l3, it2)");</p><p>  LN::iterator it3 = l4.begin(), it4 = l4.end();</p><p>  it3++; it4--;</p><p>  l1.splice(it1, l4, it3, it4);</p><p>  print(l1, "l1 after splice(it1,l4,it3,it4)");</p><p>  Noisy n;</p><p>  LN l5(3, n);</p><p>  generate_n(back_inserter(l5), 4, NoisyGen());</p><p>  l5.push_back(n);</p><p>  print(l5, "l5 before remove()");</p><p>  l5.remove(l5.front());</p><p>  print(l5, "l5 after remove()");</p><p>  l1.sort(); l5.sort();</p><p>  l5.merge(l1);</p><p>  print(l5, "l5 after l5.merge(l1)");</p><p>  cout &lt;&lt; "\n Cleanup" &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The <strong>print( )</strong> function displays results. After filling four <strong>list</strong>s with <strong>Noisy</strong> objects, one list is spliced into another in three ways. In the first, the entire list <strong>l2</strong> is spliced into <strong>l1</strong> at the iterator <strong>it1</strong>. Notice that after the splice, <strong>l2</strong> is empty—splicing means removing the elements from the source list. The second splice inserts elements from <strong>l3 </strong>starting at <strong>it2</strong> into <strong>l1 </strong>starting at <strong>it1</strong>. The third splice starts at <strong>it1</strong> and uses elements from <strong>l4</strong> starting at <strong>it3</strong> and ending at <strong>it4</strong> (the seemingly redundant mention of the source list is because the elements must be erased from the source list as part of the transfer to the destination list)<strong>.</strong></p><p>The output from the code that demonstrates <strong>remove( )</strong> shows that the list does not have to be sorted in order for all the elements of a particular value to be removed.</p><p>Finally, if you <strong>merge( )</strong> one list with another, the merge only works sensibly if the lists have been sorted. What you end up with in that case is a sorted list containing all the elements from both lists (the source list is erased—that is, the elements are <emphasis>moved</emphasis> to the destination list).</p><p>A <strong>unique( )</strong> member function removes all duplicates, but only if you sort the <strong>list</strong> first:</p><p>//: C07:UniqueList.cpp</p><p>// Testing list's unique() function</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;list&gt;</p><p>using namespace std;</p><empty-line/><p>int a[] = { 1, 3, 1, 4, 1, 5, 1, 6, 1 };</p><p>const int asz = sizeof a / sizeof *a;</p><empty-line/><p>int main() {</p><p>  // For output:</p><p>  ostream_iterator&lt;int&gt; out(cout, " ");</p><p>  list&lt;int&gt; li(a, a + asz);</p><p>  li.unique();</p><p>  // Oops! No duplicates removed:</p><p>  copy(li.begin(), li.end(), out);</p><p>  cout &lt;&lt; endl;</p><p>  // Must sort it first:</p><p>  li.sort();</p><p>  copy(li.begin(), li.end(), out);</p><p>  cout &lt;&lt; endl;</p><p>  // Now unique() will have an effect:</p><p>  li.unique();</p><p>  copy(li.begin(), li.end(), out);</p><p>  cout &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The <strong>list</strong> constructor used here takes the starting and past-the-end iterator from another container and copies all the elements from that container into itself. (A similar constructor is available for all the containers.) Here, the "container" is just an array, and the "iterators" are pointers into that array, but because of the design of the STL, it works with arrays just as easily as any other container.</p><p>The <strong>unique( )</strong> function will remove only <emphasis>adjacent</emphasis> duplicate elements, and thus sorting is necessary before calling <strong>unique( )</strong>.</p><p>Four additional <strong>list </strong>member functions are not demonstrated here: a <strong>remove_if( )</strong> that takes a predicate, which decides whether an object should be removed; a <strong>unique( )</strong> that takes a binary predicate to perform uniqueness comparisons; a <strong>merge( )</strong> that takes an additional argument which performs comparisons; and a <strong>sort( )</strong> that takes a comparator (to provide a comparison or override the existing one).</p></section><section><title><p>list vs. set</p></title><p>Looking at the previous example, you might note that if you want a sorted list with no duplicates, a <strong>set</strong> can give you that, right? It’s interesting to compare the performance of the two containers:</p><p>//: C07:ListVsSet.cpp</p><p>// Comparing list and set performance</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;list&gt;</p><p>#include &lt;set&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>using namespace std;</p><empty-line/><p>class Obj {</p><p>  int a[20]; // To take up extra space</p><p>  int val;</p><p>public:</p><p>  Obj() : val(rand() % 500) {}</p><p>  friend bool</p><p>  operator&lt;(const Obj&amp; a, const Obj&amp; b) {</p><p>    return a.val &lt; b.val;</p><p>  }</p><p>  friend bool</p><p>  operator==(const Obj&amp; a, const Obj&amp; b) {</p><p>    return a.val == b.val;</p><p>  }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Obj&amp; a) {</p><p>    return os &lt;&lt; a.val;</p><p>  }</p><p>};</p><empty-line/><p>template&lt;class Container&gt;</p><p>void print(Container&amp; c) {</p><p>  typename Container::iterator it;</p><p>  for(it = c.begin(); it != c.end(); it++)</p><p>    cout &lt;&lt; *it &lt;&lt; " ";</p><p>  cout &lt;&lt; endl;</p><p>}</p><empty-line/><p>struct ObjGen {</p><p>  Obj operator()() { return Obj(); }</p><p>};</p><empty-line/><p>int main() {</p><p>  const int sz = 5000;</p><p>  srand(time(0));</p><p>  list&lt;Obj&gt; lo;</p><p>  clock_t ticks = clock();</p><p>  generate_n(back_inserter(lo), sz, ObjGen());</p><p>  lo.sort();</p><p>  lo.unique();</p><p>  cout &lt;&lt; "list:" &lt;&lt; clock() - ticks &lt;&lt; endl;</p><p>  set&lt;Obj&gt; so;</p><p>  ticks = clock();</p><p>  generate_n(inserter(so, so.begin()),</p><p>    sz, ObjGen());</p><p>  cout &lt;&lt; "set:" &lt;&lt; clock() - ticks &lt;&lt; endl;</p><p>  print(lo);</p><p>  print(so);</p><p>} ///:~</p><empty-line/><p>When you run the program, you should discover that <strong>set</strong> is much faster than <strong>list</strong>. This is reassuring—after all, it <emphasis>is</emphasis><strong>set</strong>’s primary job description!<sup>.</sup></p></section></section></section><section><title><p>Swapping basic sequences</p></title><p>We mentioned earlier that all basic sequences have a member function <strong>swap( )</strong> that’s designed to switch one sequence with another (but only for sequences of the same type). The member <strong>swap( )</strong> makes use of its knowledge of the internal structure of the particular container in order to be efficient:</p><p>//: C07:Swapping.cpp</p><p>//{-bor}</p><p>// All basic sequence containers can be swapped</p><p>#include "Noisy.h"</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;deque&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;list&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><p>ostream_iterator&lt;Noisy&gt; out(cout, " ");</p><empty-line/><p>template&lt;class Cont&gt;</p><p>void print(Cont&amp; c, char* comment = "") {</p><p>  cout &lt;&lt; "\n" &lt;&lt; comment &lt;&lt; ": ";</p><p>  copy(c.begin(), c.end(), out);</p><p>  cout &lt;&lt; endl;</p><p>}</p><empty-line/><p>template&lt;class Cont&gt;</p><p>void testSwap(char* cname) {</p><p>  Cont c1, c2;</p><p>  generate_n(back_inserter(c1), 10, NoisyGen());</p><p>  generate_n(back_inserter(c2), 5, NoisyGen());</p><p>  cout &lt;&lt; "\n" &lt;&lt; cname &lt;&lt; ":" &lt;&lt; endl;</p><p>  print(c1, "c1"); print(c2, "c2");</p><p>  cout &lt;&lt; "\n Swapping the " &lt;&lt; cname</p><p>    &lt;&lt; ":" &lt;&lt; endl;</p><p>  c1.swap(c2);</p><p>  print(c1, "c1"); print(c2, "c2");</p><p>}</p><empty-line/><p>int main() {</p><p>  testSwap&lt;vector&lt;Noisy&gt; &gt;("vector");</p><p>  testSwap&lt;deque&lt;Noisy&gt; &gt;("deque");</p><p>  testSwap&lt;list&lt;Noisy&gt; &gt;("list");</p><p>} ///:~</p><empty-line/><p>When you run this, you’ll discover that each type of sequence container can swap one sequence for another without any copying or assignments, even if the sequences are of different sizes. In effect, you’re completely swapping the resources of one object for another.</p><p>The STL algorithms also contain a <strong>swap( )</strong>, and when this function is applied to two containers of the same type, it uses the member <strong>swap( )</strong> to achieve fast performance. Consequently, if you apply the <strong>sort( )</strong> algorithm to a container of containers, you will find that the performance is very fast—it turns out that fast sorting of a container of containers was a design goal of the STL.</p></section></section><section><title><p>set</p></title><section><p>The <strong>set</strong> produces a container that will accept only one of each thing you place in it; it also sorts the elements. (Sorting isn’t intrinsic to the conceptual definition of a set, but the STL <strong>set</strong> stores its elements in a balanced tree data structure to provide rapid lookups, thus producing sorted results when you traverse it.) The first two examples in this chapter used <strong>set</strong>s.</p><p>Consider the problem of creating an index for a book. You might like to start with all the words in the book, but you only want one instance of each word, and you want them sorted. Of course, a <strong>set</strong> is perfect for this and solves the problem effortlessly. However, there’s also the problem of punctuation and any other nonalpha characters, which must be stripped off to generate proper words. One solution to this problem is to use the Standard C library functions <strong>isalpha( )</strong> and <strong>isspace( )</strong> to extract only the characters you want. You can replace all unwanted characters with spaces so that you can easily extract valid words from each line you read:</p><p>//: C07:WordList.cpp</p><p>// Display a list of words used in a document</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cctype&gt;</p><p>#include &lt;cstring&gt;</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;set&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><p>char replaceJunk(char c) {</p><p>   // Only keep alphas, space (as a delimiter), and '</p><p>   return (isalpha(c) || c == '\'') ? c : ' ';</p><p>}</p><p>int main(int argc, char* argv[]) {</p><p>  char* fname = "WordList.cpp";</p><p>  if(argc &gt; 1) fname = argv[1];</p><p>  ifstream in(fname);</p><p>  assure(in, fname);</p><p>  set&lt;string&gt; wordlist;</p><p>  string line;</p><p>  while(getline(in, line)) {</p><p>    transform(line.begin(), line.end(), line.begin(),</p><p>              replaceJunk);</p><p>    istringstream is(line);</p><p>    string word;</p><p>    while (is &gt;&gt; word)</p><p>      wordlist.insert(word);</p><p>    }</p><p>  // Output results:</p><p>  copy(wordlist.begin(), wordlist.end(),</p><p>       ostream_iterator&lt;string&gt;(cout, "\n"));</p><p>} ///:~</p><empty-line/><p>The call to <strong>transform( )</strong> replaces each character to be ignored with a space. The set container not only ignores duplicate words, but compares the words it keeps according to the function object <strong>less&lt;string&gt;</strong> (the default second template argument for the <strong>set</strong> container), which in turn uses <strong>string::operator&lt;( )</strong>, so the words emerge in alphabetical order<sup>.</sup></p><p>You don’t have to use a <strong>set</strong> just to get a sorted sequence. You can use the <strong>sort( )</strong> function (along with a multitude of other functions in the STL) on different STL containers. However, it’s likely that <strong>set</strong> will be faster. Using a set is particularly handy when you just want to do lookup, since its <strong>find( )</strong> member function has logarithmic complexity and therefore is much faster than the generic <strong>find( )</strong> algorithm<sup>.</sup></p><p>The following version shows how to build the list of words with an <strong>istreambuf_iterator</strong> that moves the characters from one place (the input stream) to another (a <strong>string </strong>object), depending on whether the Standard C library function <strong>isalpha( )</strong> returns true:</p><p>//: C07:WordList2.cpp</p><p>// Illustrates istreambuf_iterator and insert iterators</p><p>#include &lt;cstring&gt;</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;set&gt;</p><p>#include &lt;string&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  char* fname = "WordList2.cpp";</p><p>  if(argc &gt; 1) fname = argv[1];</p><p>  ifstream in(fname);</p><p>  assure(in, fname);</p><p>  istreambuf_iterator&lt;char&gt; p(in), end;</p><p>  set&lt;string&gt; wordlist;</p><p>  while (p != end) {</p><p>    string word;</p><p>    insert_iterator&lt;string&gt;</p><p>      ii(word, word.begin());</p><p>    // Find the first alpha character:</p><p>    while(!isalpha(*p) &amp;&amp; p != end)</p><p>      p++;</p><p>    // Copy until the first non-alpha character:</p><p>    while (isalpha(*p) &amp;&amp; p != end)</p><p>      *ii++ = *p++;</p><p>    if (word.size() != 0)</p><p>      wordlist.insert(word);</p><p>  }</p><p>  // Output results:</p><p>  copy(wordlist.begin(), wordlist.end(),</p><p>    ostream_iterator&lt;string&gt;(cout, "\n"));</p><p>} ///:~</p><empty-line/><p>This example was suggested by Nathan Myers, who invented the <strong>istreambuf_iterator</strong> and its relatives. This iterator extracts information character by character from a stream. Although the <strong>istreambuf_iterator </strong>template argument might suggest that you could extract, for example, <strong>int</strong>s instead of <strong>char</strong>, that’s not the case. The argument must be of some character type—a regular <strong>char</strong> or a wide character.</p><p>After the file is open, an <strong>istreambuf_iterator</strong> called <strong>p</strong> is attached to the <strong>istream</strong> so characters can be extracted from it. The <strong>set&lt;string&gt;</strong> called <strong>wordlist</strong> will hold the resulting words.</p><p>The <strong>while</strong> loop reads words until the end of the input stream is found. This is detected using the default constructor for <strong>istreambuf_iterator,</strong> which produces the past-the-end iterator object <strong>end</strong>. Thus, if you want to test to make sure you’re not at the end of the stream, you simply say <strong>p != end</strong>.</p><p>The second type of iterator that’s used here is the <strong>insert_iterator</strong>, which creates an iterator that knows how to insert objects into a container. Here, the "container" is the <strong>string</strong> called <strong>word,</strong> which, for the purposes of <strong>insert_iterator</strong>, behaves like a container. The constructor for <strong>insert_iterator</strong> requires the container and an iterator indicating where it should start inserting the characters. You could also use a <strong>back_insert_iterator</strong>, which requires that the container have a <strong>push_back( )</strong> (<strong>string</strong> does).</p><p>After the <strong>while</strong> loop sets everything up, it begins by looking for the first alpha character, incrementing <strong>start</strong> until that character is found. It then copies characters from one iterator to the other, stopping when a nonalpha character is found. Each <strong>word</strong>, assuming it is nonempty, is added to <strong>wordlist</strong>.</p></section><section><title><p>A completely reusable tokenizer</p></title><p>The word list examples use different approaches to extract tokens from a stream, neither of which is very flexible. Since the STL containers and algorithms all revolve around iterators, the most flexible solution will itself use an iterator. You could think of the <strong>TokenIterator</strong> as an iterator that wraps itself around any other iterator that can produce characters. Because it is certainly a type of input iterator (the most primitive type of iterator), it can provide input to any STL algorithm. Not only is it a useful tool in itself, the following <strong>TokenIterator</strong> is also a good example of how you can design your own iterators.<a l:href="#n97" type="note">[97]</a></p><p>The <strong>TokenIterator</strong> class is doubly flexible. First, you can choose the type of iterator that will produce the <strong>char</strong> input. Second, instead of just saying what characters represent the delimiters, <strong>TokenIterator</strong> will use a predicate that is a function object whose <strong>operator( )</strong> takes a <strong>char</strong> and decides whether it should be in the token. Although the two examples given here have a static concept of what characters belong in a token, you could easily design your own function object to change its state as the characters are read, producing a more sophisticated parser.</p><p>The following header file contains two basic predicates, <strong>Isalpha</strong> and <strong>Delimiters</strong>, along with the template for <strong>TokenIterator</strong>:</p><p>//: C07:TokenIterator.h</p><p>#ifndef TOKENITERATOR_H</p><p>#define TOKENITERATOR_H</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cctype&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;string&gt;</p><empty-line/><p>struct Isalpha : std::unary_function&lt;char, bool&gt; {</p><p>  bool operator()(char c) {</p><p>    return std::isalpha(c);</p><p>  }</p><p>};</p><empty-line/><p>class Delimiters : std::unary_function&lt;char, bool&gt; {</p><p>  std::string exclude;</p><p>public:</p><p>  Delimiters() {}</p><p>  Delimiters(const std::string&amp; excl)</p><p>    : exclude(excl) {}</p><p>  bool operator()(char c) {</p><p>    return exclude.find(c) == std::string::npos;</p><p>  }</p><p>};</p><empty-line/><p>template &lt;class InputIter, class Pred = Isalpha&gt;</p><p>class TokenIterator : public std::iterator&lt;</p><p>    std::input_iterator_tag,std::string, std::ptrdiff_t&gt; {</p><p>  InputIter first;</p><p>  InputIter last;</p><p>  std::string word;</p><p>  Pred predicate;</p><p>public:</p><p>  TokenIterator(InputIter begin, InputIter end,</p><p>    Pred pred = Pred())</p><p>    : first(begin), last(end), predicate(pred) {</p><p>      ++*this;</p><p>  }</p><p>  TokenIterator() {} // End sentinel</p><p>  // Prefix increment:</p><p>  TokenIterator&amp; operator++() {</p><p>    word.resize(0);</p><p>    first = std::find_if(first, last, predicate);</p><p>    while (first != last &amp;&amp; predicate(*first))</p><p>      word += *first++;</p><p>    return *this;</p><p>  }</p><p>  // Postfix increment</p><p>  class Proxy {</p><p>    std::string word;</p><p>  public:</p><p>    Proxy(const std::string&amp; w) : word(w) {}</p><p>    std::string operator*() { return word; }</p><p>  };</p><p>  Proxy operator++(int) {</p><p>    Proxy d(word);</p><p>    ++*this;</p><p>    return d;</p><p>  }</p><p>  // Produce the actual value:</p><p>  std::string operator*() const { return word; }</p><p>  std::string* operator-&gt;() const {</p><p>    return &amp;(operator*());</p><p>  }</p><p>  // Compare iterators:</p><p>  bool operator==(const TokenIterator&amp;) {</p><p>    return word.size() == 0 &amp;&amp; first == last;</p><p>  }</p><p>  bool operator!=(const TokenIterator&amp; rv) {</p><p>    return !(*this == rv);</p><p>  }</p><p>};</p><p>#endif // TOKENITERATOR_H ///:~</p><empty-line/><p>The <strong>TokenIterator</strong> class derives from the <strong>std::iterator</strong> template. It might appear that some kind of functionality comes with <strong>std::iterator</strong>, but it is purely a way of tagging an iterator so that a container that uses it knows what it’s capable of. Here, you can see <strong>input_iterator_tag</strong> as the <strong>iterator_category</strong> template argument—this tells anyone who asks that a <strong>TokenIterator</strong> only has the capabilities of an input iterator and cannot be used with algorithms requiring more sophisticated iterators. Apart from the tagging, <strong>std::iterator</strong> doesn’t do anything beyond providing several useful type definitions, which means you must design all the other functionality in yourself.</p><p>The <strong>TokenIterator</strong> class may look a little strange at first, because the first constructor requires both a "begin" and an "end" iterator as arguments, along with the predicate. Remember, this is a "wrapper" iterator that has no idea how to tell whether it’s at the end of its input source, so the ending iterator is necessary in the first constructor. The reason for the second (default) constructor is that the STL algorithms (and any algorithms you write) need a <strong>TokenIterator </strong>sentinel to be the past-the-end value. Since all the information necessary to see if the <strong>TokenIterator</strong> has reached the end of its input is collected in the first constructor, this second constructor creates a <strong>TokenIterator</strong> that is merely used as a placeholder in algorithms.</p><p>The core of the behavior happens in <strong>operator++</strong>. This erases the current value of <strong>word</strong> using <strong>string::resize( )</strong> and then finds the first character that satisfies the predicate (thus discovering the beginning of the new token) using <strong>find_if( )</strong> (from the STL algorithms, discussed in the following chapter). The resulting iterator is assigned to <strong>first</strong>, thus moving <strong>first</strong> forward to the beginning of the token. Then, as long as the end of the input is not reached and the predicate is satisfied, input characters are copied into <strong>word</strong>. Finally, the <strong>TokenIterator</strong> object is returned and must be dereferenced to access the new token.</p><p>The postfix increment requires a proxy object to hold the value before the increment, so it can be returned. Producing the actual value is a straightforward <strong>operator*</strong>. The only other functions that must be defined for an output iterator are the <strong>operator==</strong> and <strong>operator!=</strong> to indicate whether the <strong>TokenIterator</strong> has reached the end of its input. You can see that the argument for <strong>operator== </strong>is ignored—it only cares about whether it has reached its internal <strong>last</strong> iterator. Notice that <strong>operator!=</strong> is defined in terms of <strong>operator==</strong>.</p><p>A good test of <strong>TokenIterator</strong> includes a number of different sources of input characters, including a <strong>streambuf_iterator</strong>, a <strong>char*</strong>, and a <strong>deque&lt;char&gt;::iterator</strong>. Finally, the original word list problem is solved:</p><p>//: C07:TokenIteratorTest.cpp</p><p>//{-msc}</p><p>#include "TokenIterator.h"</p><p>#include "../require.h"</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;vector&gt;</p><p>#include &lt;deque&gt;</p><p>#include &lt;set&gt;</p><p>using namespace std;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  char* fname = "TokenIteratorTest.cpp";</p><p>  if(argc &gt; 1) fname = argv[1];</p><p>  ifstream in(fname);</p><p>  assure(in, fname);</p><p>  ostream_iterator&lt;string&gt; out(cout, "\n");</p><p>  typedef istreambuf_iterator&lt;char&gt; IsbIt;</p><p>  IsbIt begin(in), isbEnd;</p><p>  Delimiters</p><p>    delimiters(" \t\n~;()\"&lt;&gt;:{}[]+-=&amp;*#.,/\\");</p><p>  TokenIterator&lt;IsbIt, Delimiters&gt;</p><p>    wordIter(begin, isbEnd, delimiters),</p><p>    end;</p><p>  vector&lt;string&gt; wordlist;</p><p>  copy(wordIter, end, back_inserter(wordlist));</p><p>  // Output results:</p><p>  copy(wordlist.begin(), wordlist.end(), out);</p><p>  *out++ = "-----------------------------------";</p><p>  // Use a char array as the source:</p><p>  char* cp =</p><p>    "typedef std::istreambuf_iterator&lt;char&gt; It";</p><p>  TokenIterator&lt;char*, Delimiters&gt;</p><p>    charIter(cp, cp + strlen(cp), delimiters),</p><p>    end2;</p><p>  vector&lt;string&gt; wordlist2;</p><p>  copy(charIter, end2, back_inserter(wordlist2));</p><p>  copy(wordlist2.begin(), wordlist2.end(), out);</p><p>  *out++ = "-----------------------------------";</p><p>  // Use a deque&lt;char&gt; as the source:</p><p>  ifstream in2("TokenIteratorTest.cpp");</p><p>  deque&lt;char&gt; dc;</p><p>  copy(IsbIt(in2), IsbIt(), back_inserter(dc));</p><p>  TokenIterator&lt;deque&lt;char&gt;::iterator,Delimiters&gt;</p><p>    dcIter(dc.begin(), dc.end(), delimiters),</p><p>    end3;</p><p>  vector&lt;string&gt; wordlist3;</p><p>  copy(dcIter, end3, back_inserter(wordlist3));</p><p>  copy(wordlist3.begin(), wordlist3.end(), out);</p><p>  *out++ = "-----------------------------------";</p><p>  // Reproduce the Wordlist.cpp example:</p><p>  ifstream in3("TokenIteratorTest.cpp");</p><p>  TokenIterator&lt;IsbIt, Delimiters&gt;</p><p>    wordIter2((IsbIt(in3)), isbEnd, delimiters);</p><p>  set&lt;string&gt; wordlist4;</p><p>  while(wordIter2 != end)</p><p>    wordlist4.insert(*wordIter2++);</p><p>  copy(wordlist4.begin(), wordlist4.end(), out);</p><p>} ///:~</p><empty-line/><p>When using an <strong>istreambuf_iterator</strong>, you create one to attach to the <strong>istream</strong> object and one with the default constructor as the past-the-end marker. Both are used to create the <strong>TokenIterator</strong> that will actually produce the tokens; the default constructor produces the faux <strong>TokenIterator</strong> past-the-end sentinel. (This is just a placeholder and, as mentioned previously, is actually ignored.) The <strong>TokenIterator</strong> produces <strong>string</strong>s that are inserted into a container which must, naturally, be a container of <strong>string</strong>—here a <strong>vector&lt;string&gt;</strong> is used in all cases except the last. (You could also concatenate the results onto a <strong>string.</strong>) Other than that, a <strong>TokenIterator</strong> works like any other input iterator.</p><p>The strangest thing in the previous program is the declaration of <strong>wordIter2</strong>. Note the extra parentheses in the first argument to the constructor. Without these, a conforming compiler will think that <strong>wordIter2</strong> is a prototype for a function that has three arguments and returns a <strong>TokenIterator&lt;IsbIt, Delimiters&gt;</strong>.<a l:href="#n98" type="note">[98]</a> (Microsoft’s Visual C++ .NET compiler accepts it without the extra parentheses, but it shouldn’t.)<sup>.</sup></p></section></section><section><title><p>stack</p></title><p>The <strong>stack</strong>, along with the <strong>queue</strong> and <strong>priority_queue</strong>, are classified as <emphasis>adapters</emphasis>, which means they adapt one of the basic sequence containers to store their data. This is an unfortunate case of confusing what something does with the details of its underlying implementation—the fact that these are called "adapters" is of primary value only to the creator of the library. When you use them, you generally don’t care that they’re adapters, but instead that they solve your problem. Admittedly at times it’s useful to know that you can choose an alternate implementation or build an adapter from an existing container object, but that’s generally one level removed from the adapter’s behavior. So, while you may see it emphasized elsewhere that a particular container is an adapter, we’ll only point out that fact when it’s useful. Note that each type of adapter has a default container that it’s built upon, and this default is the most sensible implementation. In most cases you won’t need to concern yourself with the underlying implementation.</p><p>The following example shows <strong>stack&lt;string&gt;</strong> implemented in the three ways: the default (which uses <strong>deque</strong>), with a <strong>vector,</strong> and with a <strong>list</strong>:</p><p>//: C07:Stack1.cpp</p><p>// Demonstrates the STL stack</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;list&gt;</p><p>#include &lt;stack&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>// Rearrange comments below to use different versions.</p><p>typedef stack&lt;string&gt; Stack1; // Default: deque&lt;string&gt;</p><p>// typedef stack&lt;string, vector&lt;string&gt; &gt; Stack2;</p><p>// typedef stack&lt;string, list&lt;string&gt; &gt; Stack3;</p><empty-line/><p>int main() {</p><p>  ifstream in("Stack1.cpp");</p><p>  Stack1 textlines; // Try the different versions</p><p>  // Read file and store lines in the stack:</p><p>  string line;</p><p>  while(getline(in, line))</p><p>    textlines.push(line + "\n");</p><p>  // Print lines from the stack and pop them:</p><p>  while(!textlines.empty()) {</p><p>    cout &lt;&lt; textlines.top();</p><p>    textlines.pop();</p><p>  }</p><p>} ///:~</p><empty-line/><p>The <strong>top( )</strong> and <strong>pop( )</strong> operations will probably seem non-intuitive if you’ve used other <strong>stack</strong> classes. When you call <strong>pop( ),</strong> it returns void rather than the top element that you might have expected. If you want the top element, you get a reference to it with <strong>top( )</strong>. It turns out this is more efficient, since a traditional <strong>pop( )</strong> would have to return a value rather than a reference and thus invoke the copy-constructor. More important, it is <emphasis>exception safe</emphasis>, as we discussed in Chapter 1. If <strong>pop( )</strong> both changed the state of the stack and attempted to return the top element, an exception in the element’s copy-constructor could cause the element to be lost. When you’re using a <strong>stack</strong> (or a <strong>priority_queue</strong>, described later), you can efficiently refer to <strong>top( )</strong> as many times as you want and then discard the top element explicitly using <strong>pop( ).</strong> (Perhaps if some term other than the familiar "pop" had been used, this would have been a bit clearer.)</p><p>The <strong>stack</strong> template has a simple interface—essentially the member functions you saw earlier. Since it only makes sense to access a stack at its top, no iterators are available for traversing it. Nor are there sophisticated forms of initialization, but if you need that, you can use the underlying container upon which the <strong>stack</strong> is implemented. For example, suppose you have a function that expects a <strong>stack</strong> interface, but in the rest of your program you need the objects stored in a <strong>list</strong>. The following program stores each line of a file along with the leading number of spaces in that line. (You might imagine it as a starting point for performing some kind of source-code reformatting.)</p><p>//: C07:Stack2.cpp</p><p>// Converting a list to a stack</p><p>#include &lt;iostream&gt;</p><p>#include &lt;fstream&gt;</p><p>#include &lt;stack&gt;</p><p>#include &lt;list&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>// Expects a stack:</p><p>template&lt;class Stk&gt;</p><p>void stackOut(Stk&amp; s, ostream&amp; os = cout) {</p><p>  while(!s.empty()) {</p><p>    os &lt;&lt; s.top() &lt;&lt; "\n";</p><p>    s.pop();</p><p>  }</p><p>}</p><empty-line/><p>class Line {</p><p>  string line; // Without leading spaces</p><p>  int lspaces; // Number of leading spaces</p><p>public:</p><p>  Line(string s) : line(s) {</p><p>    lspaces = line.find_first_not_of(' ');</p><p>    if(lspaces == string::npos)</p><p>      lspaces = 0;</p><p>    line = line.substr(lspaces);</p><p>  }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Line&amp; l) {</p><p>    for(int i = 0; i &lt; l.lspaces; i++)</p><p>      os &lt;&lt; ' ';</p><p>    return os &lt;&lt; l.line;</p><p>  }</p><p>  // Other functions here...</p><p>};</p><empty-line/><p>int main() {</p><p>  ifstream in("Stack2.cpp");</p><p>  list&lt;Line&gt; lines;</p><p>  // Read file and store lines in the list:</p><p>  string s;</p><p>  while(getline(in, s))</p><p>    lines.push_front(s);</p><p>  // Turn the list into a stack for printing:</p><p>  stack&lt;Line, list&lt;Line&gt; &gt; stk(lines);</p><p>  stackOut(stk);</p><p>} ///:~</p><empty-line/><p>The function that requires the <strong>stack</strong> interface just sends each <strong>top( )</strong> object to an <strong>ostream</strong> and then removes it by calling <strong>pop( )</strong>. The <strong>Line</strong> class determines the number of leading spaces and then stores the contents of the line <emphasis>without</emphasis> the leading spaces. The <strong>ostream operator&lt;&lt;</strong> re-inserts the leading spaces so the line prints properly, but you can easily change the number of spaces by changing the value of <strong>lspaces.</strong> (The member functions to do this are not shown here.)</p><p>In <strong>main( )</strong>, the input file is read into a <strong>list&lt;Line&gt;</strong>, and then each line in the list is copied into a <strong>stack</strong> that is sent to <strong>stackOut( )</strong>.</p><p>You cannot iterate through a <strong>stack</strong>; this emphasizes that you only want to perform <strong>stack</strong> operations when you create a <strong>stack</strong>. You can get equivalent "stack" functionality using a <strong>vector</strong> and its <strong>back( )</strong>, <strong>push_back( ),</strong> and <strong>pop_back( )</strong> member functions, and then you have all the additional functionality of the <strong>vector</strong>. <strong>Stack1.cpp</strong> can be rewritten to show this:</p><p>//: C07:Stack3.cpp</p><p>// Using a vector as a stack; modified Stack1.cpp</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  ifstream in("Stack3.cpp");</p><p>  vector&lt;string&gt; textlines;</p><p>  string line;</p><p>  while(getline(in, line))</p><p>    textlines.push_back(line + "\n");</p><p>  while(!textlines.empty()) {</p><p>    cout &lt;&lt; textlines.back();</p><p>    textlines.pop_back();</p><p>  }</p><p>} ///:~</p><empty-line/><p>This produces the same output as <strong>Stack1.cpp</strong>, but you can now perform <strong>vector</strong> operations as well. Of course, <strong>list</strong> can also push things at the front, but it’s generally less efficient than using <strong>push_back( )</strong> with <strong>vector</strong>. (In addition, <strong>deque</strong> is usually more efficient than <strong>list</strong> for pushing things at the front.)</p></section><section><title><p>queue</p></title><p>The <strong>queue</strong> is a restricted form of a <strong>deque</strong>—you can only enter elements at one end and pull them off the other end. Functionally, you could use a <strong>deque</strong> anywhere you need a <strong>queue</strong>, and you would then also have the additional functionality of the <strong>deque</strong>. The only reason you need to use a <strong>queue</strong> rather than a <strong>deque</strong>, then, is if you want to emphasize that you will only be performing queue-like behavior.</p><p>The <strong>queue</strong> is an adapter class like <strong>stack</strong>, in that it is built on top of another sequence container. As you might guess, the ideal implementation for a <strong>queue</strong> is a <strong>deque</strong>, and that is the default template argument for the <strong>queue</strong>; you’ll rarely need a different implementation.</p><p>Queues are often used when modeling systems in which some elements of the system are waiting to be served by other elements in the system. A classic example of this is the "bank-teller problem": customers arrive at random intervals, get into a line, and then are served by a set of tellers. Since the customers arrive randomly and each takes a random amount of time to be served, there’s no way to deterministically know how long the line will be at any time. However, it’s possible to simulate the situation and see what happens.</p><p>In a realistic simulation each customer and teller should be run by a separate thread. What we’d like is a multithreaded environment so that each customer or teller would have their own thread. However, Standard C++ has no model for multithreading, so there is no standard solution to this problem. On the other hand, with a little adjustment to the code, it’s possible to simulate enough multithreading to provide a satisfactory solution.<a l:href="#n99" type="note">[99]</a></p><p>In multithreading, multiple threads of control run simultaneously, sharing the same address space. Quite often you have fewer CPUs than you do threads (and often only one CPU). To give the illusion that each thread has its own CPU, a <emphasis>time-slicing</emphasis> mechanism says "OK, current thread, you’ve had enough time. I’m going to stop you and give time to some other thread." This automatic stopping and starting of threads is called <emphasis>preemptive, </emphasis>and it means you (the programmer) don’t need to manage the threading process at all.</p><p>An alternative approach has each thread voluntarily yield the CPU to the scheduler, which then finds another thread that needs running. Instead, we’ll build the "time-slicing" into the classes in the system. In this case, it will be the tellers that represent the "threads," (the customers will be passive). Each teller will have an infinite-looping <strong>run( )</strong> member function that will execute for a certain number of "time units" and then simply return. By using the ordinary return mechanism, we eliminate the need for any swapping. The resulting program, although small, provides a remarkably reasonable simulation:</p><p>//: C07:BankTeller.cpp</p><p>// Using a queue and simulated multithreading</p><p>// To model a bank teller system</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;list&gt;</p><p>#include &lt;queue&gt;</p><p>using namespace std;</p><empty-line/><p>class Customer {</p><p>  int serviceTime;</p><p>public:</p><p>  Customer() : serviceTime(0) {}</p><p>  Customer(int tm) : serviceTime(tm) {}</p><p>  int getTime() { return serviceTime; }</p><p>  void setTime(int newtime) {</p><p>    serviceTime = newtime;</p><p>  }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Customer&amp; c) {</p><p>    return os &lt;&lt; '[' &lt;&lt; c.serviceTime &lt;&lt; ']';</p><p>  }</p><p>};</p><empty-line/><p>class Teller {</p><p>  queue&lt;Customer&gt;&amp; customers;</p><p>  Customer current;</p><p>  enum { slice = 5 };</p><p>  int ttime; // Time left in slice</p><p>  bool busy; // Is teller serving a customer?</p><p>public:</p><p>  Teller(queue&lt;Customer&gt;&amp; cq)</p><p>    : customers(cq), ttime(0), busy(false) {}</p><p>  Teller&amp; operator=(const Teller&amp; rv) {</p><p>    customers = rv.customers;</p><p>    current = rv.current;</p><p>    ttime = rv.ttime;</p><p>    busy = rv.busy;</p><p>    return *this;</p><p>  }</p><p>  bool isBusy() { return busy; }</p><p>  void run(bool recursion = false) {</p><p>    if(!recursion)</p><p>      ttime = slice;</p><p>    int servtime = current.getTime();</p><p>    if(servtime &gt; ttime) {</p><p>      servtime -= ttime;</p><p>      current.setTime(servtime);</p><p>      busy = true; // Still working on current</p><p>      return;</p><p>    }</p><p>    if(servtime &lt; ttime) {</p><p>      ttime -= servtime;</p><p>      if(!customers.empty()) {</p><p>        current = customers.front();</p><p>        customers.pop(); // Remove it</p><p>        busy = true;</p><p>        run(true); // Recurse</p><p>      }</p><p>      return;</p><p>    }</p><p>    if(servtime == ttime) {</p><p>      // Done with current, set to empty:</p><p>      current = Customer(0);</p><p>      busy = false;</p><p>      return; // No more time in this slice</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>// Inherit to access protected implementation:</p><p>class CustomerQ : public queue&lt;Customer&gt; {</p><p>public:</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const CustomerQ&amp; cd) {</p><p>    copy(cd.c.begin(), cd.c.end(),</p><p>      ostream_iterator&lt;Customer&gt;(os, ""));</p><p>    return os;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  CustomerQ customers;</p><p>  list&lt;Teller&gt; tellers;</p><p>  typedef list&lt;Teller&gt;::iterator TellIt;</p><p>  tellers.push_back(Teller(customers));</p><p>  srand(time(0)); // Seed random number generator</p><p>  clock_t ticks = clock();</p><p>  // Run simulation for at least 5 seconds:</p><p>  while(clock() &lt; ticks + 5 * CLOCKS_PER_SEC) {</p><p>    // Add a random number of customers to the</p><p>    // queue, with random service times:</p><p>    for(int i = 0; i &lt; rand() % 5; i++)</p><p>      customers.push(Customer(rand() % 15 + 1));</p><p>    cout &lt;&lt; '{' &lt;&lt; tellers.size() &lt;&lt; '}'</p><p>      &lt;&lt; customers &lt;&lt; endl;</p><p>    // Have the tellers service the queue:</p><p>    for(TellIt i = tellers.begin();</p><p>      i != tellers.end(); i++)</p><p>      (*i).run();</p><p>    cout &lt;&lt; '{' &lt;&lt; tellers.size() &lt;&lt; '}'</p><p>      &lt;&lt; customers &lt;&lt; endl;</p><p>    // If line is too long, add another teller:</p><p>    if(customers.size() / tellers.size() &gt; 2)</p><p>      tellers.push_back(Teller(customers));</p><p>    // If line is short enough, remove a teller:</p><p>    if(tellers.size() &gt; 1 &amp;&amp;</p><p>      customers.size() / tellers.size() &lt; 2)</p><p>      for(TellIt i = tellers.begin();</p><p>        i != tellers.end(); i++)</p><p>        if(!(*i).isBusy()) {</p><p>          tellers.erase(i);</p><p>          break; // Out of for loop</p><p>        }</p><p>  }</p><p>} ///:~</p><empty-line/><p>Each customer requires a certain amount of service time, which is the number of time units that a teller must spend on the customer to serve that customer’s needs. Of course, the amount of service time will be different for each customer and will be determined randomly. In addition, you won’t know how many customers will be arriving in each interval, so this will also be determined randomly<sup>.</sup></p><p>The <strong>Customer </strong>objects are kept in a <strong>queue&lt;Customer&gt;</strong>, and each <strong>Teller</strong> object keeps a reference to that queue. When a <strong>Teller</strong> object is finished with its current <strong>Customer</strong> object, that <strong>Teller</strong> will get another <strong>Customer</strong> from the queue and begin working on the new <strong>Customer</strong>, reducing the <strong>Customer</strong>’s service time during each time slice that the <strong>Teller</strong> is allotted. All this logic is in the <strong>run( )</strong> member function, which is basically a three-way <strong>if</strong> statement based on whether the amount of time necessary to serve the customer is less than, greater than, or equal to the amount of time left in the teller’s current time slice. Notice that if the <strong>Teller</strong> has more time after finishing with a <strong>Customer</strong>, it gets a new customer and recurses into itself<sup>.</sup></p><p>Just as with a <strong>stack</strong>, when you use a <strong>queue</strong>, it’s only a <strong>queue</strong> and doesn’t have any of the other functionality of the basic sequence containers. This includes the ability to get an iterator in order to step through the <strong>stack</strong>. However, the underlying sequence container (that the <strong>queue</strong> is built upon) is held as a <strong>protected</strong> member inside the <strong>queue</strong>, and the identifier for this member is specified in the C++ Standard as ‘<strong>c</strong>’, which means that you can derive from <strong>queue</strong> to access the underlying implementation. The <strong>CustomerQ</strong> class does exactly that, for the sole purpose of defining an <strong>ostream operator&lt;&lt;</strong> that can iterate through the <strong>queue</strong> and print out its members.</p><p>The driver for the simulation is the <strong>while</strong> loop in <strong>main( )</strong>, which uses processor ticks (defined in <strong>&lt;ctime&gt;</strong>) to determine if the simulation has run for at least 5 seconds. At the beginning of each pass through the loop, a random number of customers is added, with random service times. Both the number of tellers and the queue contents are displayed so you can see the state of the system. After running each teller, the display is repeated. At this point, the system adapts by comparing the number of customers and the number of tellers; if the line is too long, another teller is added, and if it is short enough, a teller can be removed. In this adaptation section of the program you can experiment with policies regarding the optimal addition and removal of tellers. If this is the only section that you’re modifying, you might want to encapsulate policies inside different objects. We’ll revisit this problem with a multithreaded solution in Chapter 10<sup>.</sup></p></section><section><title><p>Priority queues</p></title><p>When you <strong>push( )</strong> an object onto a <strong>priority_queue</strong>, that object is sorted into the queue according to a function or function object. (You can allow the default <strong>less</strong> template to supply this, or you can provide one of your own.) The <strong>priority_queue</strong> ensures that when you look at the <strong>top( )</strong> element, it will be the one with the highest priority. When you’re done with it, you call <strong>pop( )</strong> to remove it and bring the next one into place. Thus, the <strong>priority_queue</strong> has nearly the same interface as a <strong>stack</strong>, but it behaves differently.</p><p>Like <strong>stack</strong> and <strong>queue</strong>, <strong>priority_queue</strong> is an adapter that is built on top of one of the basic sequences—the default is <strong>vector</strong>.</p><p>It’s trivial to make a <strong>priority_queue</strong> that works with <strong>int</strong>s:</p><p>//: C07:PriorityQueue1.cpp</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;queue&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  priority_queue&lt;int&gt; pqi;</p><p>  srand(time(0)); // Seed random number generator</p><p>  for(int i = 0; i &lt; 100; i++)</p><p>    pqi.push(rand() % 25);</p><p>  while(!pqi.empty()) {</p><p>    cout &lt;&lt; pqi.top() &lt;&lt; ' ';</p><p>    pqi.pop();</p><p>  }</p><p>} ///:~</p><empty-line/><p>This pushes into the <strong>priority_queue </strong>100 random values from 0 to 24. When you run this program you’ll see that duplicates are allowed, and the highest values appear first. To show how you can change the ordering by providing your own function or function object, the following program gives lower-valued numbers the highest priority:</p><p>//: C07:PriorityQueue2.cpp</p><p>// Changing the priority</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;functional&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;queue&gt;</p><p>using namespace std;</p><p>int main() {</p><p>  priority_queue&lt;int, vector&lt;int&gt;, greater&lt;int&gt; &gt; pqi;</p><p>  srand(time(0));</p><p>  for(int i = 0; i &lt; 100; i++)</p><p>    pqi.push(rand() % 25);</p><p>  while(!pqi.empty()) {</p><p>    cout &lt;&lt; pqi.top() &lt;&lt; ' ';</p><p>    pqi.pop();</p><p>  }</p><p>} ///:~</p><empty-line/><p>A more interesting problem is a to-do list, in which each object contains a <strong>string</strong> and a primary and secondary priority value:</p><p>//: C07:PriorityQueue3.cpp</p><p>// A more complex use of priority_queue</p><p>#include &lt;iostream&gt;</p><p>#include &lt;queue&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>class ToDoItem {</p><p>  char primary;</p><p>  int secondary;</p><p>  string item;</p><p>public:</p><p>  ToDoItem(string td, char pri ='A', int sec =1)</p><p>    : item(td), primary(pri), secondary(sec) {}</p><p>  friend bool operator&lt;(</p><p>    const ToDoItem&amp; x, const ToDoItem&amp; y) {</p><p>    if(x.primary &gt; y.primary)</p><p>      return true;</p><p>    if(x.primary == y.primary)</p><p>      if(x.secondary &gt; y.secondary)</p><p>        return true;</p><p>    return false;</p><p>  }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const ToDoItem&amp; td) {</p><p>    return os &lt;&lt; td.primary &lt;&lt; td.secondary</p><p>      &lt;&lt; ": " &lt;&lt; td.item;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  priority_queue&lt;ToDoItem&gt; toDoList;</p><p>  toDoList.push(ToDoItem("Empty trash", 'C', 4));</p><p>  toDoList.push(ToDoItem("Feed dog", 'A', 2));</p><p>  toDoList.push(ToDoItem("Feed bird", 'B', 7));</p><p>  toDoList.push(ToDoItem("Mow lawn", 'C', 3));</p><p>  toDoList.push(ToDoItem("Water lawn", 'A', 1));</p><p>  toDoList.push(ToDoItem("Feed cat", 'B', 1));</p><p>  while(!toDoList.empty()) {</p><p>    cout &lt;&lt; toDoList.top() &lt;&lt; endl;</p><p>    toDoList.pop();</p><p>  }</p><p>} ///:~</p><empty-line/><p>The <strong>ToDoItem</strong>’s <strong>operator&lt;</strong> must be a nonmember function for it to work with <strong>less&lt; &gt;</strong>. Other than that, everything happens automatically. The output is:</p><p>A1: Water lawn</p><p>A2: Feed dog</p><p>B1: Feed cat</p><p>B7: Feed bird</p><p>C3: Mow lawn</p><p>C4: Empty trash</p><empty-line/><p>You cannot iterate through a <strong>priority_queue</strong>, but it’s possible to simulate the behavior of a <strong>priority_queue</strong> using a <strong>vector</strong>, thus allowing you access to that <strong>vector</strong>. You can do this by looking at the implementation of <strong>priority_queue</strong>, which uses <strong>make_heap( )</strong>, <strong>push_heap( ),</strong> and <strong>pop_heap( ).</strong> (They are the soul of the <strong>priority_queue</strong>; in fact you could say that the heap <emphasis>is</emphasis> the priority queue and that <strong>priority_queue </strong>is just a wrapper around it.) This turns out to be reasonably straightforward, but you might think that a shortcut is possible. Since the container used by <strong>priority_queue</strong> is <strong>protected</strong> (and has the identifier, according to the Standard C++ specification, named <strong>c</strong>), you can inherit a new class that provides access to the underlying implementation:</p><p>//: C07:PriorityQueue4.cpp</p><p>// Manipulating the underlying implementation</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;queue&gt;</p><p>using namespace std;</p><empty-line/><p>class PQI : public priority_queue&lt;int&gt; {</p><p>public:</p><p>  vector&lt;int&gt;&amp; impl() { return c; }</p><p>};</p><empty-line/><p>int main() {</p><p>  PQI pqi;</p><p>  srand(time(0));</p><p>  for(int i = 0; i &lt; 100; i++)</p><p>    pqi.push(rand() % 25);</p><p>  copy(pqi.impl().begin(), pqi.impl().end(),</p><p>    ostream_iterator&lt;int&gt;(cout, " "));</p><p>  cout &lt;&lt; endl;</p><p>  while(!pqi.empty()) {</p><p>    cout &lt;&lt; pqi.top() &lt;&lt; ' ';</p><p>    pqi.pop();</p><p>  }</p><p>} ///:~</p><empty-line/><p>However, if you run this program, you’ll discover that the <strong>vector</strong> doesn’t contain the items in the descending order that you get when you call <strong>pop( )</strong>, the order that you want from the priority queue. It would seem that if you want to create a <strong>vector</strong> that is a priority queue, you have to do it by hand, like this:</p><p>//: C07:PriorityQueue5.cpp</p><p>// Building your own priority queue</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;queue&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T, class Compare&gt;</p><p>class PQV : public vector&lt;T&gt; {</p><p>  Compare comp;</p><p>public:</p><p>  PQV(Compare cmp = Compare()) : comp(cmp) {</p><p>    make_heap(begin(), end(), comp);</p><p>  }</p><p>  const T&amp; top() { return front(); }</p><p>  void push(const T&amp; x) {</p><p>    push_back(x);</p><p>    push_heap(begin(), end(), comp);</p><p>  }</p><p>  void pop() {</p><p>    pop_heap(begin(), end(), comp);</p><p>    pop_back();</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  PQV&lt;int, less&lt;int&gt; &gt; pqi;</p><p>  srand(time(0));</p><p>  for(int i = 0; i &lt; 100; i++)</p><p>    pqi.push(rand() % 25);</p><p>  copy(pqi.begin(), pqi.end(),</p><p>    ostream_iterator&lt;int&gt;(cout, " "));</p><p>  cout &lt;&lt; endl;</p><p>  while(!pqi.empty()) {</p><p>    cout &lt;&lt; pqi.top() &lt;&lt; ' ';</p><p>    pqi.pop();</p><p>  }</p><p>} ///:~</p><empty-line/><p>But this program behaves in the same way as the previous one! What you are seeing in the underlying <strong>vector</strong> is called a <emphasis>heap</emphasis>. This heap data structure represents the tree of the priority queue (stored in the linear structure of the <strong>vector</strong>), but when you iterate through it, you do not get a linear priority-queue order. You might think that you can simply call <strong>sort_heap( )</strong>, but that only works once, and then you don’t have a heap anymore, but instead a sorted list. This means that to go back to using it as a heap, the user must remember to call <strong>make_heap( ) </strong>first. This can be encapsulated into your custom priority queue:</p><p>//: C07:PriorityQueue6.cpp</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;queue&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T, class Compare&gt;</p><p>class PQV : public vector&lt;T&gt; {</p><p>  Compare comp;</p><p>  bool sorted;</p><p>  void assureHeap() {</p><p>    if(sorted) {</p><p>      // Turn it back into a heap:</p><p>      make_heap(begin(), end(), comp);</p><p>      sorted = false;</p><p>    }</p><p>  }</p><p>public:</p><p>  PQV(Compare cmp = Compare()) : comp(cmp) {</p><p>    make_heap(begin(), end(), comp);</p><p>    sorted = false;</p><p>  }</p><p>  const T&amp; top() {</p><p>    assureHeap();</p><p>    return front();</p><p>  }</p><p>  void push(const T&amp; x) {</p><p>    assureHeap();</p><p>    // Put it at the end:</p><p>    push_back(x);</p><p>    // Re-adjust the heap:</p><p>    push_heap(begin(), end(), comp);</p><p>  }</p><p>  void pop() {</p><p>    assureHeap();</p><p>    // Move the top element to the last position:</p><p>    pop_heap(begin(), end(), comp);</p><p>    // Remove that element:</p><p>    pop_back();</p><p>  }</p><p>  void sort() {</p><p>    if(!sorted) {</p><p>      sort_heap(begin(), end(), comp);</p><p>      reverse(begin(), end());</p><p>      sorted = true;</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  PQV&lt;int, less&lt;int&gt; &gt; pqi;</p><p>  srand(time(0));</p><p>  for(int i = 0; i &lt; 100; i++) {</p><p>    pqi.push(rand() % 25);</p><p>    copy(pqi.begin(), pqi.end(),</p><p>      ostream_iterator&lt;int&gt;(cout, " "));</p><p>    cout &lt;&lt; "\n-----\n";</p><p>  }</p><p>  pqi.sort();</p><p>  copy(pqi.begin(), pqi.end(),</p><p>    ostream_iterator&lt;int&gt;(cout, " "));</p><p>  cout &lt;&lt; "\n-----\n";</p><p>  while(!pqi.empty()) {</p><p>    cout &lt;&lt; pqi.top() &lt;&lt; ' ';</p><p>    pqi.pop();</p><p>  }</p><p>} ///:~</p><empty-line/><p>If <strong>sorted</strong> is true, the <strong>vector</strong> is not organized as a heap, but instead as a sorted sequence. The <strong>assureHeap( )</strong> function guarantees that it’s put back into heap form before performing any heap operations on it.</p><p>The first <strong>for</strong> loop in <strong>main( )</strong> now has the additional quality that it displays the heap as it’s being built.</p><p>The only drawback to this solution is that the user must remember to call <strong>sort( ) </strong>before viewing it as a sorted sequence (although one could conceivably override all the member functions that produce iterators so that they guarantee sorting). Another solution is to build a priority queue that is not a <strong>vector</strong>, but will build you a <strong>vector</strong> whenever you want one:</p><p>//: C07:PriorityQueue7.cpp</p><p>// A priority queue that will hand you a vector</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;queue&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T, class Compare&gt;</p><p>class PQV {</p><p>  vector&lt;T&gt; v;</p><p>  Compare comp;</p><p>public:</p><p>  // Don't need to call make_heap(); it's empty:</p><p>  PQV(Compare cmp = Compare()) : comp(cmp) {}</p><p>  void push(const T&amp; x) {</p><p>    // Put it at the end:</p><p>    v.push_back(x);</p><p>    // Re-adjust the heap:</p><p>    push_heap(v.begin(), v.end(), comp);</p><p>  }</p><p>  void pop() {</p><p>    // Move the top element to the last position:</p><p>    pop_heap(v.begin(), v.end(), comp);</p><p>    // Remove that element:</p><p>    v.pop_back();</p><p>  }</p><p>  const T&amp; top() { return v.front(); }</p><p>  bool empty() const { return v.empty(); }</p><p>  int size() const { return v.size(); }</p><p>  typedef vector&lt;T&gt; TVec;</p><p>  TVec vector() {</p><p>    TVec r(v.begin(), v.end());</p><p>    // It’s already a heap</p><p>    sort_heap(r.begin(), r.end(), comp);</p><p>    // Put it into priority-queue order:</p><p>    reverse(r.begin(), r.end());</p><p>    return r;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  PQV&lt;int, less&lt;int&gt; &gt; pqi;</p><p>  srand(time(0));</p><p>  for(int i = 0; i &lt; 100; i++)</p><p>    pqi.push(rand() % 25);</p><p>  const vector&lt;int&gt;&amp; v = pqi.vector();</p><p>  copy(v.begin(), v.end(),</p><p>    ostream_iterator&lt;int&gt;(cout, " "));</p><p>  cout &lt;&lt; "\n-----------\n";</p><p>  while(!pqi.empty()) {</p><p>    cout &lt;&lt; pqi.top() &lt;&lt; ' ';</p><p>    pqi.pop();</p><p>  }</p><p>} ///:~</p><empty-line/><p>The <strong>PQV</strong> class template follows the same form as the STL’s <strong>priority_queue</strong>, but has the additional member <strong>vector( )</strong>, which creates a new <strong>vector</strong> that’s a copy of the one in <strong>PQV </strong>(which means that it’s already a heap). It then sorts that copy (leaving <strong>PQV</strong>’s <strong>vector</strong> untouched), and reverses the order so that traversing the new <strong>vector</strong> produces the same effect as popping the elements from the priority queue<sup>.</sup></p><p>You may observe that the approach of deriving from <strong>priority_queue</strong> used in <strong>PriorityQueue4.cpp</strong> could be used with the above technique to produce more succinct code:</p><p>//: C07:PriorityQueue8.cpp</p><p>// A more compact version of PriorityQueue7.cpp</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;queue&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T&gt;</p><p>class PQV : public priority_queue&lt;T&gt; {</p><p>public:</p><p>  typedef vector&lt;T&gt; TVec;</p><p>  TVec vector() {</p><p>    TVec r(c.begin(), c.end());</p><p>    // c is already a heap</p><p>    sort_heap(r.begin(), r.end(), comp);</p><p>    // Put it into priority-queue order:</p><p>    reverse(r.begin(), r.end());</p><p>    return r;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  PQV&lt;int&gt; pqi;</p><p>  srand(time(0));</p><p>  for(int i = 0; i &lt; 100; i++)</p><p>    pqi.push(rand() % 25);</p><p>  const vector&lt;int&gt;&amp; v = pqi.vector();</p><p>  copy(v.begin(), v.end(),</p><p>    ostream_iterator&lt;int&gt;(cout, " "));</p><p>  cout &lt;&lt; "\n-----------\n";</p><p>  while(!pqi.empty()) {</p><p>    cout &lt;&lt; pqi.top() &lt;&lt; ' ';</p><p>    pqi.pop();</p><p>  }</p><p>} ///:~</p><empty-line/><p>The brevity of this solution makes it the simplest and most desirable, plus it’s guaranteed that the user will not have a <strong>vector</strong> in the unsorted state. The only potential problem is that the <strong>vector( )</strong> member function returns the <strong>vector&lt;T&gt;</strong> by value, which might cause some overhead issues with complex values of the parameter type <strong>T</strong>.</p></section><section><title><p>Holding bits</p></title><section><p>Because C was a language that purported to be "close to the hardware," many have found it dismaying that there was no native binary representation for numbers. Decimal, of course, and hexadecimal (tolerable only because it’s easier to group the bits in your mind), but octal? Ugh. Whenever you read specs for chips you’re trying to program, they don’t describe the chip registers in octal or even hexadecimal—they use binary. And yet C won’t let you say <strong>0b0101101</strong>, which is the obvious solution for a language close to the hardware.</p><p>Although there’s still no native binary representation in C++, things have improved with the addition of two classes: <strong>bitset</strong> and <strong>vector&lt;bool&gt;</strong>, both of which are designed to manipulate a group of on-off values.<a l:href="#n100" type="note">[100]</a> The primary differences between these types are:</p><p>1.Each <strong>bitset</strong> holds a fixed number of bits. You establish the quantity of bits in the <strong>bitset</strong> template argument. The <strong>vector&lt;bool&gt;</strong> can, like a regular <strong>vector</strong>, expand dynamically to hold any number of <strong>bool</strong> values.</p><p>2.The <strong>bitset</strong> template is explicitly designed for performance when manipulating bits, and is not a "regular" STL container. As such, it has no iterators. The number of bits, being a template parameter, is known at compile time and allows the underlying integral array to be stored on the runtime stack. The <strong>vector&lt;bool&gt;</strong> container, on the other hand, is a specialization of a <strong>vector</strong> and so has all the operations of a normal <strong>vector</strong>—the specialization is just designed to be space efficient for <strong>bool</strong>.</p><p>There is no trivial conversion between a <strong>bitset</strong> and a <strong>vector&lt;bool&gt;</strong>, which implies that the two are for very different purposes. Furthermore, neither is a traditional "STL container." The <strong>bitset</strong> template class has an interface for bit-level operations and in no way resembles the STL containers we’ve discussed up to this point. The <strong>vector&lt;bool&gt;</strong> specialization of <strong>vector</strong> is similar to an STL-like container, but it differs as discussed below<sup>.</sup></p></section><section><title><p>bitset&lt;n&gt;</p></title><p>The template for <strong>bitset</strong> accepts an unsigned integral template argument that is the number of bits to represent. Thus, <strong>bitset&lt;10&gt;</strong> is a different type than <strong>bitset&lt;20&gt;</strong>, and you cannot perform comparisons, assignments, and so on between the two.</p><p>A <strong>bitset</strong> provides the most commonly used bitwise operations in an efficient form. However, each <strong>bitset</strong> is implemented by logically packing bits in an array of integral types (typically <strong>unsigned long</strong>s, which contain at least 32 bits). In addition, the only conversion from a <strong>bitset</strong> to a numerical value is to an <strong>unsigned long</strong> (via the function <strong>to_ulong( )</strong>).</p><p>The following example tests almost all the functionality of the <strong>bitset</strong> (the missing operations are redundant or trivial). You’ll see the description of each of the bitset outputs to the right of the output so that the bits all line up, and you can compare them to the source values. If you still don’t understand bitwise operations, running this program should help.</p><p>//: C07:BitSet.cpp</p><p>//{-bor}</p><p>// Exercising the bitset class</p><p>#include &lt;bitset&gt;</p><p>#include &lt;climits&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><p>const int sz = 32;</p><p>typedef bitset&lt;sz&gt; BS;</p><empty-line/><p>template&lt;int bits&gt;</p><p>bitset&lt;bits&gt; randBitset() {</p><p>  bitset&lt;bits&gt; r(rand());</p><p>  for(int i = 0; i &lt; bits/16 - 1; i++) {</p><p>    r &lt;&lt;= 16;</p><p>    // "OR" together with a new lower 16 bits:</p><p>    r |= bitset&lt;bits&gt;(rand());</p><p>  }</p><p>  return r;</p><p>}</p><empty-line/><p>int main() {</p><p>  srand(time(0));</p><p>  cout &lt;&lt; "sizeof(bitset&lt;16&gt;) = "</p><p>    &lt;&lt; sizeof(bitset&lt;16&gt;) &lt;&lt; endl;</p><p>  cout &lt;&lt; "sizeof(bitset&lt;32&gt;) = "</p><p>    &lt;&lt; sizeof(bitset&lt;32&gt;) &lt;&lt; endl;</p><p>  cout &lt;&lt; "sizeof(bitset&lt;48&gt;) = "</p><p>    &lt;&lt; sizeof(bitset&lt;48&gt;) &lt;&lt; endl;</p><p>  cout &lt;&lt; "sizeof(bitset&lt;64&gt;) = "</p><p>    &lt;&lt; sizeof(bitset&lt;64&gt;) &lt;&lt; endl;</p><p>  cout &lt;&lt; "sizeof(bitset&lt;65&gt;) = "</p><p>    &lt;&lt; sizeof(bitset&lt;65&gt;) &lt;&lt; endl;</p><p>  BS a(randBitset&lt;sz&gt;()), b(randBitset&lt;sz&gt;());</p><p>  // Converting from a bitset:</p><p>  unsigned long ul = a.to_ulong();</p><p>  cout &lt;&lt; a &lt;&lt; endl;</p><p>  // Converting a string to a bitset:</p><p>  string cbits("111011010110111");</p><p>  cout &lt;&lt; "as a string = " &lt;&lt; cbits &lt;&lt;endl;</p><p>  cout &lt;&lt; BS(cbits) &lt;&lt; " [BS(cbits)]" &lt;&lt; endl;</p><p>  cout &lt;&lt; BS(cbits, 2)</p><p>    &lt;&lt; " [BS(cbits, 2)]" &lt;&lt; endl;</p><p>  cout &lt;&lt; BS(cbits, 2, 11)</p><p>    &lt;&lt; " [BS(cbits, 2, 11)]" &lt;&lt; endl;</p><p>  cout &lt;&lt; a &lt;&lt; " [a]" &lt;&lt; endl;</p><p>  cout &lt;&lt; b &lt;&lt; " [b]" &lt;&lt; endl;</p><p>  // Bitwise AND:</p><p>  cout &lt;&lt; (a &amp; b) &lt;&lt; " [a &amp; b]" &lt;&lt; endl;</p><p>  cout &lt;&lt; (BS(a) &amp;= b) &lt;&lt; " [a &amp;= b]" &lt;&lt; endl;</p><p>  // Bitwise OR:</p><p>  cout &lt;&lt; (a | b) &lt;&lt; " [a | b]" &lt;&lt; endl;</p><p>  cout &lt;&lt; (BS(a) |= b) &lt;&lt; " [a |= b]" &lt;&lt; endl;</p><p>  // Exclusive OR:</p><p>  cout &lt;&lt; (a ^ b) &lt;&lt; " [a ^ b]" &lt;&lt; endl;</p><p>  cout &lt;&lt; (BS(a) ^= b) &lt;&lt; " [a ^= b]" &lt;&lt; endl;</p><p>  cout &lt;&lt; a &lt;&lt; " [a]" &lt;&lt; endl; // For reference</p><p>  // Logical left shift (fill with zeros):</p><p>  cout &lt;&lt; (BS(a) &lt;&lt;= sz/2)</p><p>    &lt;&lt; " [a &lt;&lt;= (sz/2)]" &lt;&lt; endl;</p><p>  cout &lt;&lt; (a &lt;&lt; sz/2) &lt;&lt; endl;</p><p>  cout &lt;&lt; a &lt;&lt; " [a]" &lt;&lt; endl; // For reference</p><p>  // Logical right shift (fill with zeros):</p><p>  cout &lt;&lt; (BS(a) &gt;&gt;= sz/2)</p><p>    &lt;&lt; " [a &gt;&gt;= (sz/2)]" &lt;&lt; endl;</p><p>  cout &lt;&lt; (a &gt;&gt; sz/2) &lt;&lt; endl;</p><p>  cout &lt;&lt; a &lt;&lt; " [a]" &lt;&lt; endl; // For reference</p><p>  cout &lt;&lt; BS(a).set() &lt;&lt; " [a.set()]" &lt;&lt; endl;</p><p>  for(int i = 0; i &lt; sz; i++)</p><p>    if(!a.test(i)) {</p><p>      cout &lt;&lt; BS(a).set(i)</p><p>        &lt;&lt; " [a.set(" &lt;&lt; i &lt;&lt;")]" &lt;&lt; endl;</p><p>      break; // Just do one example of this</p><p>    }</p><p>  cout &lt;&lt; BS(a).reset() &lt;&lt; " [a.reset()]"&lt;&lt; endl;</p><p>  for(int j = 0; j &lt; sz; j++)</p><p>    if(a.test(j)) {</p><p>      cout &lt;&lt; BS(a).reset(j)</p><p>        &lt;&lt; " [a.reset(" &lt;&lt; j &lt;&lt;")]" &lt;&lt; endl;</p><p>      break; // Just do one example of this</p><p>    }</p><p>  cout &lt;&lt; BS(a).flip() &lt;&lt; " [a.flip()]" &lt;&lt; endl;</p><p>  cout &lt;&lt; ~a &lt;&lt; " [~a]" &lt;&lt; endl;</p><p>  cout &lt;&lt; a &lt;&lt; " [a]" &lt;&lt; endl; // For reference</p><p>  cout &lt;&lt; BS(a).flip(1) &lt;&lt; " [a.flip(1)]"&lt;&lt; endl;</p><p>  BS c;</p><p>  cout &lt;&lt; c &lt;&lt; " [c]" &lt;&lt; endl;</p><p>  cout &lt;&lt; "c.count() = " &lt;&lt; c.count() &lt;&lt; endl;</p><p>  cout &lt;&lt; "c.any() = "</p><p>    &lt;&lt; (c.any() ? "true" : "false") &lt;&lt; endl;</p><p>  cout &lt;&lt; "c.none() = "</p><p>    &lt;&lt; (c.none() ? "true" : "false") &lt;&lt; endl;</p><p>  c[1].flip(); c[2].flip();</p><p>  cout &lt;&lt; c &lt;&lt; " [c]" &lt;&lt; endl;</p><p>  cout &lt;&lt; "c.count() = " &lt;&lt; c.count() &lt;&lt; endl;</p><p>  cout &lt;&lt; "c.any() = "</p><p>    &lt;&lt; (c.any() ? "true" : "false") &lt;&lt; endl;</p><p>  cout &lt;&lt; "c.none() = "</p><p>    &lt;&lt; (c.none() ? "true" : "false") &lt;&lt; endl;</p><p>  // Array indexing operations:</p><p>  c.reset();</p><p>  for(int k = 0; k &lt; c.size(); k++)</p><p>    if(k % 2 == 0)</p><p>      c[k].flip();</p><p>  cout &lt;&lt; c &lt;&lt; " [c]" &lt;&lt; endl;</p><p>  c.reset();</p><p>  // Assignment to bool:</p><p>  for(int ii = 0; ii &lt; c.size(); ii++)</p><p>    c[ii] = (rand() % 100) &lt; 25;</p><p>  cout &lt;&lt; c &lt;&lt; " [c]" &lt;&lt; endl;</p><p>  // bool test:</p><p>  if(c[1])</p><p>    cout &lt;&lt; "c[1] == true";</p><p>  else</p><p>    cout &lt;&lt; "c[1] == false" &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>To generate interesting random <strong>bitset</strong>s, the <strong>randBitset( )</strong> function is created. This function demonstrates <strong>operator&lt;&lt;=</strong> by shifting each 16 random bits to the left until the <strong>bitset</strong> (which is templatized in this function for size) is full. The generated number and each new 16 bits are combined using the <strong>operator|=</strong>.</p><p>The first thing demonstrated in <strong>main( )</strong> is the unit size of a <strong>bitset</strong>. If it is less than 32 bits, <strong>sizeof</strong> produces 4 (4 bytes = 32 bits), which is the size of a single <strong>long</strong> on most implementations. If it’s between 32 and 64, it requires two <strong>long</strong>s, greater than 64 requires 3 <strong>long</strong>s, and so on. Thus, you make the best use of space if you use a bit quantity that fits in an integral number of <strong>long</strong>s. However, notice there’s no extra overhead for the object—it’s as if you were hand-coding to use a <strong>long</strong>.</p><p>Although there are no other numerical conversions from <strong>bitset</strong> besides <strong>to_ulong( )</strong>, there is a <strong>stream inserter </strong>that produces a <strong>string</strong> containing ones and zeros, and this can be as long as the actual <strong>bitset</strong><sup><strong>.</strong></sup></p><p>There’s still no primitive format for binary values, but the next best thing is supported by <strong>bitset</strong>: a <strong>string</strong> of ones and zeros with the least-significant bit (lsb) on the right. The three constructors demonstrated show taking the entire <strong>string</strong>, the <strong>string</strong> starting at character 2, and the string from character 2 through 11. You can write to an <strong>ostream</strong> from a <strong>bitset</strong> using <strong>operator&lt;&lt;, </strong>and it comes out as ones and zeros. You can also read from an <strong>istream</strong> using <strong>operator&gt;&gt;</strong> (not shown here).</p><p>You’ll notice that <strong>bitset</strong> only has three nonmember operators: <emphasis>and</emphasis> (<strong>&amp;</strong>), <emphasis>or</emphasis> (<strong>|</strong>), and <emphasis>exclusive-or</emphasis> (<strong>^</strong>). Each of these creates a new <strong>bitset </strong>as its return value. All the member operators opt for the more efficient <strong>&amp;=</strong>, <strong>|=</strong>, and so on form in which a temporary is not created. However, these forms actually change the <strong>bitset</strong>’s value (which is <strong>a</strong> in most of the tests in the above example). To prevent this, we created a temporary to be used as the lvalue by invoking the copy-constructor on <strong>a</strong>; this is why you see the form <strong>BS(a)</strong>. The result of each test is printed out, and occasionally <strong>a</strong> is reprinted so you can easily look at it for reference.</p><p>The rest of the example should be self-explanatory when you run it; if not you can find the details in your compiler’s documentation or in the other documentation mentioned earlier in this chapter.</p></section><section><title><p>vector&lt;bool&gt;</p></title><p>The <strong>vector&lt;bool&gt;</strong> container is a specialization of the <strong>vector</strong> template. A normal <strong>bool</strong> variable requires at least one byte, but since a <strong>bool</strong> only has two states, the ideal implementation of <strong>vector&lt;bool&gt;</strong> is such that each <strong>bool</strong> value only requires one bit. This means the iterator must be specially defined and cannot be a pointer to <strong>bool</strong>.</p><p>The bit-manipulation functions for <strong>vector&lt;bool&gt;</strong> are much more limited than those of <strong>bitset</strong>. The only member function that was added to those already in <strong>vector</strong> is <strong>flip( )</strong>, to invert all the bits; there is no <strong>set( )</strong> or <strong>reset( )</strong> as in <strong>bitset</strong>. When you use <strong>operator[ ]</strong>, you get back an object of type <strong>vector&lt;bool&gt;::reference</strong>, which also has a <strong>flip( )</strong> to invert that individual bit.</p><p>//: C07:VectorOfBool.cpp</p><p>// Demonstrate the vector&lt;bool&gt; specialization</p><p>#include &lt;bitset&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  vector&lt;bool&gt; vb(10, true);</p><p>  vector&lt;bool&gt;::iterator it;</p><p>  for(it = vb.begin(); it != vb.end(); it++)</p><p>    cout &lt;&lt; *it;</p><p>  cout &lt;&lt; endl;</p><p>  vb.push_back(false);</p><p>  ostream_iterator&lt;bool&gt; out(cout, "");</p><p>  copy(vb.begin(), vb.end(), out);</p><p>  cout &lt;&lt; endl;</p><p>  bool ab[] = { true, false, false, true, true,</p><p>    true, true, false, false, true };</p><p>  // There's a similar constructor:</p><p>  vb.assign(ab, ab + sizeof(ab)/sizeof(bool));</p><p>  copy(vb.begin(), vb.end(), out);</p><p>  cout &lt;&lt; endl;</p><p>  vb.flip(); // Flip all bits</p><p>  copy(vb.begin(), vb.end(), out);</p><p>  cout &lt;&lt; endl;</p><p>  for(size_t i = 0; i &lt; vb.size(); i++)</p><p>    vb[i] = 0; // (Equivalent to "false")</p><p>  vb[4] = true;</p><p>  vb[5] = 1;</p><p>  vb[7].flip(); // Invert one bit</p><p>  copy(vb.begin(), vb.end(), out);</p><p>  cout &lt;&lt; endl;</p><p>  // Convert to a bitset:</p><p>  ostringstream os;</p><p>  copy(vb.begin(), vb.end(),</p><p>    ostream_iterator&lt;bool&gt;(os, ""));</p><p>  bitset&lt;10&gt; bs(os.str());</p><p>  cout &lt;&lt; "Bitset:\n" &lt;&lt; bs &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The last part of this example takes a <strong>vector&lt;bool&gt;</strong> and converts it to a <strong>bitset</strong> by first turning it into a <strong>string</strong> of ones and zeros. Of course, you must know the size of the <strong>bitset</strong> at compile time. You can see that this conversion is not the kind of operation you’ll want to do on a regular basis.</p><p>The <strong>vector&lt;bool&gt;</strong> specialization is a "crippled" STL container in the sense that certain guarantees that other containers provide are missing. For example, with the other containers the following relationships hold:</p><p>// Let c be an STL container other than vector&lt;bool&gt;:</p><p>T&amp; r = c.front();</p><p>T* p = &amp;*c.begin();</p><empty-line/><p>For all other containers, the <strong>front( )</strong> function yields an lvalue (something you can get a non-const reference to), and <strong>begin( )</strong> must yield something you can dereference and then take the address of. Neither is possible because bits are not addressable. Both <strong>vector&lt;bool&gt;</strong> and <strong>bitset</strong> use a proxy class (<strong>reference</strong>, mentioned earlier) to read and set bits as necessary.</p></section></section><section><title><p>Associative containers</p></title><section><p>The <strong>set</strong>, <strong>map</strong>, <strong>multiset,</strong> and <strong>multimap</strong> are called <emphasis>associative containers</emphasis> because they associate <emphasis>keys</emphasis> with <emphasis>values</emphasis>. Well, at least <strong>map</strong>s and <strong>multimap</strong>s associate keys with values, but you can look at a <strong>set</strong> as a <strong>map</strong> that has no values, only keys (and they can in fact be implemented this way), and the same for the relationship between <strong>multiset</strong> and <strong>multimap</strong>. So, because of the structural similarity, <strong>set</strong>s and <strong>multiset</strong>s are lumped in with associative containers.</p><p>The most important basic operations with associative containers are putting things in and, in the case of a <strong>set</strong>, seeing if something is in the set. In the case of a <strong>map</strong>, you want to first see if a key is in the <strong>map</strong>, and if it exists, you want the associated value for that key to be returned. Of course, there are many variations on this theme, but that’s the fundamental concept. The following example shows these basics:</p><p>//: C07:AssociativeBasics.cpp</p><p>//{-bor}</p><p>// Basic operations with sets and maps</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;map&gt;</p><p>#include &lt;set&gt;</p><p>#include "Noisy.h"</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  Noisy na[7];</p><p>  // Add elements via constructor:</p><p>  set&lt;Noisy&gt; ns(na, na + sizeof na/sizeof(Noisy));</p><p>  // Ordinary insertion:</p><p>  Noisy n;</p><p>  ns.insert(n);</p><p>  cout &lt;&lt; endl;</p><p>  // Check for set membership:</p><p>  cout &lt;&lt; "ns.count(n)= " &lt;&lt; ns.count(n) &lt;&lt; endl;</p><p>  if(ns.find(n) != ns.end())</p><p>    cout &lt;&lt; "n(" &lt;&lt; n &lt;&lt; ") found in ns" &lt;&lt; endl;</p><p>  // Print elements:</p><p>  copy(ns.begin(), ns.end(),</p><p>    ostream_iterator&lt;Noisy&gt;(cout, " "));</p><p>  cout &lt;&lt; endl;</p><p>  cout &lt;&lt; "\n-----------\n";</p><p>  map&lt;int, Noisy&gt; nm;</p><p>  for(int i = 0; i &lt; 10; i++)</p><p>    nm[i]; // Automatically makes pairs</p><p>  cout &lt;&lt; "\n-----------\n";</p><p>  for(size_t j = 0; j &lt; nm.size(); j++)</p><p>    cout &lt;&lt; "nm[" &lt;&lt; j &lt;&lt;"] = " &lt;&lt; nm[j] &lt;&lt; endl;</p><p>  cout &lt;&lt; "\n-----------\n";</p><p>  nm[10] = n;</p><p>  cout &lt;&lt; "\n-----------\n";</p><p>  nm.insert(make_pair(47, n));</p><p>  cout &lt;&lt; "\n-----------\n";</p><p>  cout &lt;&lt; "\n nm.count(10)= "</p><p>    &lt;&lt; nm.count(10) &lt;&lt; endl;</p><p>  cout &lt;&lt; "nm.count(11)= "</p><p>    &lt;&lt; nm.count(11) &lt;&lt; endl;</p><p>  map&lt;int, Noisy&gt;::iterator it = nm.find(6);</p><p>  if(it != nm.end())</p><p>    cout &lt;&lt; "value:" &lt;&lt; (*it).second</p><p>      &lt;&lt; " found in nm at location 6" &lt;&lt; endl;</p><p>  for(it = nm.begin(); it != nm.end(); it++)</p><p>    cout &lt;&lt; (*it).first &lt;&lt; ":"</p><p>      &lt;&lt; (*it).second &lt;&lt; ", ";</p><p>  cout &lt;&lt; "\n-----------\n";</p><p>} ///:~</p><empty-line/><p>The <strong>set&lt;Noisy&gt;</strong> object <strong>ns</strong> is created using two iterators into an array of <strong>Noisy</strong> objects, but there is also a default constructor and a copy-constructor, and you can pass in an object that provides an alternate scheme for doing comparisons. Both <strong>set</strong>s and <strong>map</strong>s have an <strong>insert( )</strong> member function to put things in, and you can check to see if an object is already in an associative container in a couple of ways. The <strong>count( ) </strong>member function, when given a key, will tell you how many times that key occurs. (This can only be zero or one in a <strong>set</strong> or <strong>map</strong>, but it can be more than one with a <strong>multiset</strong> or <strong>multimap.</strong>) The <strong>find( )</strong> member function will produce an iterator indicating the first occurrence (with <strong>set</strong> and <strong>map</strong>, the <emphasis>only</emphasis> occurrence) of the key that you give it or will produce the past-the-end iterator if it can’t find the key. The <strong>count( )</strong> and <strong>find( )</strong> member functions exist for all the associative containers, which makes sense. The associative containers also have member functions <strong>lower_bound( )</strong>, <strong>upper_bound( ),</strong> and <strong>equal_range( )</strong>, which actually only make sense for <strong>multiset</strong> and <strong>multimap</strong>, as you will see. (But don’t try to figure out how they would be useful for <strong>set</strong> and <strong>map</strong>, since they are designed for dealing with a range of duplicate keys, which those containers don’t allow.)</p><p>Designing an <strong>operator[ ]</strong> always presents a bit of a dilemma. Because it’s intended to be treated as an array-indexing operation, people don’t tend to think about performing a test before they use it. But what happens if you decide to index out of the bounds of the array? One option, of course, is to throw an exception, but with a <strong>map</strong> "indexing out of the array" could mean that you want an entry there, and that’s the way the STL <strong>map</strong> treats it. The first <strong>for</strong> loop after the creation of the <strong>map&lt;int, Noisy&gt; nm</strong> just "looks up" objects using the <strong>operator[ ]</strong>, but this is actually creating new <strong>Noisy</strong> objects! The <strong>map</strong> creates a new key-value pair (using the default constructor for the value) if you look up a value with <strong>operator[ ]</strong> and it isn’t there. This means that if you really just want to look something up and not create a new entry, you must use the member functions <strong>count( )</strong> (to see if it’s there) or <strong>find( )</strong> (to get an iterator to it).</p><p>A number of problems are associated with the <strong>for</strong> loop that prints the values of the container using <strong>operator[ ]</strong>. First, it requires integral keys (which we happen to have in this case). Next and worse, if all the keys are not sequential, you’ll end up counting from zero to the size of the container, and if some spots don’t have key-value pairs, you’ll automatically create them and miss some of the higher values of the keys. Finally, if you look at the output from the <strong>for</strong> loop, you’ll see that things are <emphasis>very</emphasis> busy, and it’s quite puzzling at first why there are so many constructions and destructions for what appears to be a simple lookup. The answer only becomes clear when you look at the code in the <strong>map</strong> template for <strong>operator[ ]</strong>, which will be something like this:</p><p>mapped_type&amp; operator[] (const key_type&amp; k) {</p><p>  value_type tmp(k,T());</p><p>  return (*((insert(tmp)).first)).second;</p><p>}</p><empty-line/><p>The <strong>map::insert( )</strong> function takes a key-value pair and does nothing if there is already an entry in the map with the given key—otherwise it inserts an entry for the key. In either case, it returns a new key-value pair holding an iterator to the inserted pair as its first element and holding true as the second element if an insertion actually took place. The members <strong>first</strong> and <strong>second</strong> give the key and value, respectively, because <strong>map::value_type</strong> is really just a <strong>typedef</strong> for a <strong>std::pair</strong>:</p><p>typedef pair&lt;const Key, T&gt; value_type;</p><empty-line/><p>We’ve seen the <strong>std::pair</strong> template before, which just holds two values of independent types, as you can see by its definition:</p><p>template &lt;class T1, class T2&gt;</p><p>struct pair {</p><p>  typedef T1 first_type;</p><p>  typedef T2 second_type;</p><p>  T1 first;</p><p>  T2 second;</p><p>  pair();</p><p>  pair(const T1&amp; x, const T2&amp; y)</p><p>    : first(x), second(y) {}</p><p>  // Templatized copy-constructor:</p><p>  template&lt;class U, class V&gt;</p><p>   pair(const pair&lt;U, V&gt; &amp;p);</p><p>};</p><empty-line/><p>The <strong>pair</strong> template class is very useful, especially when you want to return two objects from a function (since a <strong>return</strong> statement only takes one object). There’s even a shorthand for creating a pair called <strong>make_pair( )</strong>, which is used in <strong>AssociativeBasics.cpp</strong>.</p><p>So to retrace the steps, <strong>map::value_type</strong> is a <strong>pair</strong> of the key and the value of the map—actually, it’s a single entry for the map. But notice that <strong>pair</strong> packages its objects by value, which means that copy-constructions are necessary to get the objects into the <strong>pair</strong>. Thus, the creation of <strong>tmp</strong> in <strong>map::operator[ ]</strong> will involve at least a copy-constructor call and destructor call for each object in the <strong>pair</strong>. Here, we’re getting off easy because the key is an <strong>int</strong>. But if you want to really see what kind of activity can result from <strong>map::operator[ ]</strong>, try running this:</p><p>//: C07:NoisyMap.cpp</p><p>// Mapping Noisy to Noisy</p><p>//{L} ../TestSuite/Test</p><p>#include "Noisy.h"</p><p>#include &lt;map&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  map&lt;Noisy, Noisy&gt; mnn;</p><p>  Noisy n1, n2;</p><p>  cout &lt;&lt; "\n--------\n";</p><p>  mnn[n1] = n2;</p><p>  cout &lt;&lt; "\n--------\n";</p><p>  cout &lt;&lt; mnn[n1] &lt;&lt; endl;</p><p>  cout &lt;&lt; "\n--------\n";</p><p>} ///:~</p><empty-line/><p>You’ll see that both the insertion and lookup generate a lot of extra objects, and that’s because of the creation of the <strong>tmp</strong> object. If you look back up at <strong>map::operator[ ],</strong> you’ll see that the second line calls <strong>insert( ),</strong> passing it <strong>tmp</strong>—that is, <strong>operator[ ]</strong> does an insertion every time. The return value of <strong>insert( )</strong> is a different kind of <strong>pair</strong>, in which <strong>first</strong> is an iterator pointing to the key-value <strong>pair</strong> that was just inserted, and <strong>second</strong> is a <strong>bool</strong> indicating whether the insertion took place. You can see that <strong>operator[ ]</strong> grabs <strong>first</strong> (the iterator), dereferences it to produce the <strong>pair</strong>, and then returns the <strong>second,</strong> which is the value at that location<sup>.</sup></p><p>So on the upside, <strong>map</strong> has this fancy "make a new entry if one isn’t there" behavior, but the downside is that you <emphasis>always</emphasis> get a lot of extra object creations and destructions when you use <strong>map::operator[ ]</strong>. Fortunately, <strong>AssociativeBasics.cpp</strong> also demonstrates how to reduce the overhead of insertions and deletions, by not using <strong>operator[ ]</strong> if you don’t have to. The <strong>insert( )</strong> member function is slightly more efficient than <strong>operator[ ]</strong>. With a <strong>set,</strong> you hold only one object, but with a <strong>map,</strong> you hold key-value pairs; so <strong>insert( )</strong> requires a <strong>pair</strong> as its argument. Here’s where <strong>make_pair( )</strong> comes in handy, as you can see.</p><p>For looking objects up in a <strong>map</strong>, you can use <strong>count( )</strong> to see whether a key is in the map, or you can use <strong>find( )</strong> to produce an iterator pointing directly at the key-value pair. Again, since the <strong>map</strong> contains <strong>pair</strong>s, that’s what the iterator produces when you dereference it; so you have to select <strong>first</strong> and <strong>second</strong>. When you run <strong>AssociativeBasics.cpp,</strong> you’ll notice that the iterator approach involves no extra object creations or destructions at all. It’s not as easy to write or read, though.</p></section><section><title><p>Generators and fillers for associative containers</p></title><p>You’ve seen how useful the <strong>fill( )</strong>, <strong>fill_n( )</strong>, <strong>generate( ),</strong> and <strong>generate_n( )</strong> function templates in <strong>&lt;algorithm&gt;</strong> have been for filling the sequential containers (<strong>vector</strong>, <strong>list,</strong> and <strong>deque</strong>) with data. However, these are implemented by using <strong>operator= </strong>to assign values into the sequential containers, and the way that you add objects to associative containers is with their respective <strong>insert( )</strong> member functions. Thus, the default "assignment" behavior causes a problem when trying to use the "fill" and "generate" functions with associative containers.</p><p>One solution is to duplicate the "fill" and "generate" functions, creating new ones that can be used with associative containers. It turns out that only the <strong>fill_n( )</strong> and <strong>generate_n( )</strong> functions can be duplicated (<strong>fill( ) </strong>and <strong>generate( ) </strong>copy in between two iterators, which doesn’t make sense with associative containers), but the job is fairly easy, since you have the <strong>&lt;algorithm&gt;</strong> header file to work from (and since it contains templates, all the source code is there):</p><p>//: C07:assocGen.h</p><p>// The fill_n() and generate_n() equivalents</p><p>// for associative containers.</p><p>#ifndef ASSOCGEN_H</p><p>#define ASSOCGEN_H</p><empty-line/><p>template&lt;class Assoc, class Count, class T&gt;</p><p>void</p><p>assocFill_n(Assoc&amp; a, Count n, const T&amp; val) {</p><p>  while(n-- &gt; 0)</p><p>    a.insert(val);</p><p>}</p><empty-line/><p>template&lt;class Assoc, class Count, class Gen&gt;</p><p>void assocGen_n(Assoc&amp; a, Count n, Gen g) {</p><p>  while(n-- &gt; 0)</p><p>    a.insert(g());</p><p>}</p><p>#endif // ASSOCGEN_H ///:~</p><empty-line/><p>You can see that instead of using iterators, the container class itself is passed (by reference, of course, since you wouldn’t want to make a local copy, fill it, and then have it discarded at the end of the scope).</p><p>This code demonstrates two valuable lessons. The first is that if the algorithms don’t do what you want, copy the nearest thing and modify it. You have the example at hand in the STL header, so most of the work has already been done.</p><p>The second lesson is more pointed: if you look long enough, there’s probably a way to do it in the STL <emphasis>without</emphasis> inventing anything new. The present problem can instead be solved by using an <strong>insert_iterator</strong> (produced by a call to <strong>inserter( )</strong>), which calls <strong>insert( )</strong> to place items in the container instead of <strong>operator=</strong>. This is <emphasis>not</emphasis> simply a variation of <strong>front_insert_iterator</strong> or <strong>back_insert_iterator</strong>, because those iterators use <strong>push_front( )</strong> and <strong>push_back( )</strong>, respectively. Each of the insert iterators is different by virtue of the member function it uses for insertion, and <strong>insert( )</strong> is the one we need. Here’s a demonstration that shows filling and generating both a <strong>map</strong> and a <strong>set.</strong> (Of course, it can also be used with <strong>multimap</strong> and <strong>multiset.</strong>) First, some templatized, simple generators are created. (This may seem like overkill, but you never know when you’ll need them; for that reason they’re placed in a header file.)</p><p>//: C07:SimpleGenerators.h</p><p>// Generic generators, including</p><p>// one that creates pairs</p><p>#include &lt;iostream&gt;</p><p>#include &lt;utility&gt;</p><empty-line/><p>// A generator that increments its value:</p><p>template&lt;typename T&gt;</p><p>class IncrGen {</p><p>  T i;</p><p>public:</p><p>  IncrGen(T ii) : i (ii) {}</p><p>  T operator()() { return i++; }</p><p>};</p><empty-line/><p>// A generator that produces an STL pair&lt;&gt;:</p><p>template&lt;typename T1, typename T2&gt;</p><p>class PairGen {</p><p>  T1 i;</p><p>  T2 j;</p><p>public:</p><p>  PairGen(T1 ii, T2 jj) : i(ii), j(jj) {}</p><p>  std::pair&lt;T1,T2&gt; operator()() {</p><p>    return std::pair&lt;T1,T2&gt;(i++, j++);</p><p>  }</p><p>};</p><empty-line/><p>namespace std {</p><p>// A generic global operator&lt;&lt;</p><p>// for printing any STL pair&lt;&gt;:</p><p>template&lt;typename F, typename S&gt; ostream&amp;</p><p>operator&lt;&lt;(ostream&amp; os, const pair&lt;F,S&gt;&amp; p) {</p><p>  return os &lt;&lt; p.first &lt;&lt; "\t"</p><p>    &lt;&lt; p.second &lt;&lt; endl;</p><p>}} ///:~</p><empty-line/><p>Both generators expect that <strong>T</strong> can be incremented, and they simply use <strong>operator++</strong> to generate new values from whatever you used for initialization. <strong>PairGen</strong> creates an STL <strong>pair</strong> object as its return value, and that’s what can be placed into a <strong>map</strong> or <strong>multimap</strong> using <strong>insert( )</strong>.</p><p>The last function is a generalization of <strong>operator&lt;&lt;</strong> for <strong>ostream</strong>s, so that any <strong>pair</strong> can be printed, assuming each element of the <strong>pair </strong>supports a stream <strong>operator&lt;&lt;</strong>. (It is in namespace <strong>std</strong> for the strange name lookup reasons discussed in Chapter 5.) As you can see in the following, this allows the use of <strong>copy( )</strong> to output the <strong>map</strong>:</p><p>//: C07:AssocInserter.cpp</p><p>// Using an insert_iterator so fill_n() and</p><p>// generate_n() can be used with associative</p><p>// containers</p><p>#include "SimpleGenerators.h"</p><p>#include &lt;iterator&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;set&gt;</p><p>#include &lt;map&gt;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  set&lt;int&gt; s;</p><p>  fill_n(inserter(s, s.begin()), 10, 47);</p><p>  generate_n(inserter(s, s.begin()), 10,</p><p>    IncrGen&lt;int&gt;(12));</p><p>  copy(s.begin(), s.end(),</p><p>    ostream_iterator&lt;int&gt;(cout, "\n"));</p><empty-line/><p>  map&lt;int, int&gt; m;</p><p>  fill_n(inserter(m, m.begin()), 10,</p><p>    make_pair(90,120));</p><p>  generate_n(inserter(m, m.begin()), 10,</p><p>    PairGen&lt;int, int&gt;(3, 9));</p><p>  copy(m.begin(), m.end(),</p><p>    ostream_iterator&lt;pair&lt;int,int&gt; &gt;(cout,"\n"));</p><p>} ///:~</p><empty-line/><p>The second argument to <strong>inserter</strong> is an iterator, which is an optimization hint to help the insertion go faster (instead of always starting the search at the root of the underlying tree). Since an <strong>insert_iterator</strong> can be used with many different types of containers, with non-associative containers it is more than a hint—it is required<sup>.</sup></p><p>Note how the <strong>ostream_iterator</strong> is created to output a <strong>pair</strong>; this wouldn’t have worked if the <strong>operator&lt;&lt;</strong> hadn’t been created, and since it’s a template, it is automatically instantiated for <strong>pair&lt;int, int&gt;</strong>.</p></section><section><title><p>The magic of maps</p></title><p>An ordinary array uses an integral value to index into a sequential set of elements of some type. A <strong>map</strong> is an <emphasis>associative array</emphasis>, which means you associate one object with another in an array-like fashion, but instead of selecting an array element with a number as you do with an ordinary array, you look it up with an object! The example that follows counts the words in a text file, so the index is the <strong>string</strong> object representing the word, and the value being looked up is the object that keeps count of the strings.</p><p>In a single-item container such as a <strong>vector</strong> or a <strong>list</strong>, only one thing is being held. But in a <strong>map</strong>, you’ve got two things: the <emphasis>key</emphasis> (what you look up by, as in <strong>mapname[key]</strong>) and the <emphasis>value</emphasis> that results from the lookup with the key. If you simply want to move through the entire <strong>map</strong> and list each key-value pair, you use an iterator, which when dereferenced produces a <strong>pair</strong> object containing both the key and the value. You access the members of a <strong>pair</strong> by selecting <strong>first</strong> or <strong>second</strong>.</p><p>This same philosophy of packaging two items together is also used to insert elements into the map, but the <strong>pair</strong> is created as part of the instantiated <strong>map</strong> and is called <strong>value_type</strong>, containing the key and the value. So one option for inserting a new element is to create a <strong>value_type</strong> object, loading it with the appropriate objects and then calling the <strong>insert( )</strong> member function for the <strong>map</strong>. Instead, the following example uses the aforementioned special feature of <strong>map</strong>: if you’re trying to find an object by passing in a key to <strong>operator[ ]</strong> and that object doesn’t exist, <strong>operator[ ]</strong> will automatically insert a new key-value pair for you, using the default constructor for the value object. With that in mind, consider an implementation of a word-counting program:</p><p>//: C07:WordCount.cpp</p><p>// Count occurrences of words using a map</p><p>#include "../require.h"</p><p>#include &lt;string&gt;</p><p>#include &lt;map&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;fstream&gt;</p><p>using namespace std;</p><empty-line/><p>typedef map&lt;string, int&gt; WordMap;</p><p>typedef WordMap::iterator WMIter;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  char* fname = "WordCount.cpp";</p><p>  if(argc &gt; 1) fname = argv[1];</p><p>  ifstream in(fname);</p><p>  assure(in, fname);</p><p>  WordMap wordmap;</p><p>  string word;</p><p>  while(in &gt;&gt; word)</p><p>    wordmap[word]++;</p><p>  for(WMIter w = wordmap.begin(); w != wordmap.end(); w++)</p><p>    cout &lt;&lt; w-&gt;first &lt;&lt; ": "</p><p>      &lt;&lt; w-&gt;second &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>This example shows the power of <emphasis>zero-initialization</emphasis>. Consider this line of code from the program above:<sup>.</sup></p><p>wordmap[word]++;</p><empty-line/><p>This increments the <strong>int</strong> associated with <strong>word</strong>. If there isn’t such a word yet in the map, a key-value pair for the word is automatically inserted, with the value initialized to zero by a call to the pseudo-constructor <strong>int( )</strong>, which returns a 0<sup>.</sup></p><p>Printing the entire list requires traversing it with an iterator. (There’s no <strong>copy( )</strong> shortcut for a <strong>map</strong> unless you want to write an <strong>operator&lt;&lt; </strong>for the <strong>pair</strong> in the map.) As previously mentioned, dereferencing this iterator produces a <strong>pair</strong> object, with the <strong>first</strong> member the key and the <strong>second</strong> member the value<sup>.</sup></p><p>If you want to find the count for a particular word, you can use the array index operator, like this:</p><p>cout &lt;&lt; "the: " &lt;&lt; wordmap["the"] &lt;&lt; endl;</p><empty-line/><p>You can see that one of the great advantages of the <strong>map</strong> is the clarity of the syntax; an associative array makes intuitive sense to the reader. (Note, however, that if "the" isn’t already in the <strong>wordmap,</strong> a new entry will be created!)</p></section><section><title><p>Multimaps and duplicate keys</p></title><p>A <strong>multimap</strong> is a <strong>map</strong> that can contain duplicate keys. At first this may seem like a strange idea, but it can occur surprisingly often. A phone book, for example, can have many entries with the same name<sup>.</sup></p><p>Suppose you are monitoring wildlife, and you want to keep track of where and when each type of animal is spotted. Thus, you may see many animals of the same kind, all in different locations and at different times. So if the type of animal is the key, you’ll need a <strong>multimap</strong>. Here’s what it looks like:</p><p>//: C07:WildLifeMonitor.cpp</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;map&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>class DataPoint {</p><p>  int x, y; // Location coordinates</p><p>  time_t time; // Time of Sighting</p><p>public:</p><p>  DataPoint() : x(0), y(0), time(0) {}</p><p>  DataPoint(int xx, int yy, time_t tm) :</p><p>    x(xx), y(yy), time(tm) {}</p><p>  // Synthesized operator=, copy-constructor OK</p><p>  int getX() const { return x; }</p><p>  int getY() const { return y; }</p><p>  const time_t* getTime() const { return &amp;time; }</p><p>};</p><empty-line/><p>string animal[] = {</p><p>  "chipmunk", "beaver", "marmot", "weasel",</p><p>  "squirrel", "ptarmigan", "bear", "eagle",</p><p>  "hawk", "vole", "deer", "otter", "hummingbird",</p><p>};</p><p>const int asz = sizeof animal/sizeof *animal;</p><p>vector&lt;string&gt; animals(animal, animal + asz);</p><empty-line/><p>// All the information is contained in a</p><p>// "Sighting," which can be sent to an ostream:</p><p>typedef pair&lt;string, DataPoint&gt; Sighting;</p><empty-line/><p>ostream&amp;</p><p>operator&lt;&lt;(ostream&amp; os, const Sighting&amp; s) {</p><p>  return os &lt;&lt; s.first &lt;&lt; " sighted at x= " &lt;&lt;</p><p>    s.second.getX() &lt;&lt; ", y= " &lt;&lt; s.second.getY()</p><p>    &lt;&lt; ", time = " &lt;&lt; ctime(s.second.getTime());</p><p>}</p><empty-line/><p>// A generator for Sightings:</p><p>class SightingGen {</p><p>  vector&lt;string&gt;&amp; animals;</p><p>  enum { d = 100 };</p><p>public:</p><p>  SightingGen(vector&lt;string&gt;&amp; an) :</p><p>    animals(an) { srand(time(0)); }</p><p>  Sighting operator()() {</p><p>    Sighting result;</p><p>    int select = rand() % animals.size();</p><p>    result.first = animals[select];</p><p>    result.second = DataPoint(</p><p>      rand() % d, rand() % d, time(0));</p><p>    return result;</p><p>  }</p><p>};</p><empty-line/><p>// Display a menu of animals, allow the user to</p><p>// select one, return the index value:</p><p>int menu() {</p><p>  cout &lt;&lt; "select an animal or 'q' to quit: ";</p><p>  for(int i = 0; i &lt; animals.size(); i++)</p><p>    cout &lt;&lt;'['&lt;&lt; i &lt;&lt;']'&lt;&lt; animals[i] &lt;&lt; ' ';</p><p>  cout &lt;&lt; endl;</p><p>  string reply;</p><p>  cin &gt;&gt; reply;</p><p>  if(reply.at(0) == 'q') return 0;</p><p>  istringstream r(reply);</p><p>  int i;</p><p>  r &gt;&gt; i; // Converts to int</p><p>  i %= animals.size();</p><p>  return i;</p><p>}</p><empty-line/><p>typedef multimap&lt;string, DataPoint&gt; DataMap;</p><p>typedef DataMap::iterator DMIter;</p><empty-line/><p>int main() {</p><p>  DataMap sightings;</p><p>  generate_n(</p><p>    inserter(sightings, sightings.begin()),</p><p>    50, SightingGen(animals));</p><p>  // Print everything:</p><p>  copy(sightings.begin(), sightings.end(),</p><p>    ostream_iterator&lt;Sighting&gt;(cout, ""));</p><p>  // Print sightings for selected animal:</p><p>  for(int count = 1; count &lt; 10; count++) {</p><p>    // Use menu to get selection:</p><p>    // int i = menu();</p><p>    // Generate randomly (for automated testing):</p><p>    int i = rand() % animals.size();</p><p>    // Iterators in "range" denote begin, one</p><p>    // past end of matching range:</p><p>    pair&lt;DMIter, DMIter&gt; range =</p><p>      sightings.equal_range(animals[i]);</p><p>    copy(range.first, range.second,</p><p>      ostream_iterator&lt;Sighting&gt;(cout, ""));</p><p>  }</p><p>} ///:~</p><empty-line/><p>All the data about a sighting is encapsulated into the class <strong>DataPoint</strong>, which is simple enough that it can rely on the synthesized assignment and copy-constructor. It uses the Standard C library time functions to record the time of the sighting.</p><p>In the array of <strong>string animal</strong>, notice that the <strong>char*</strong> constructor is automatically used during initialization, which makes initializing an array of <strong>string</strong> quite convenient. Since it’s easier to use the animal names in a <strong>vector</strong>, the length of the array is calculated, and a <strong>vector&lt;string&gt;</strong> is initialized using the <strong>vector(iterator, iterator)</strong> constructor.</p><p>The key-value pairs that make up a <strong>Sighting</strong> are the <strong>string,</strong> which names the type of animal, and the <strong>DataPoint,</strong> which says where and when it was sighted. The standard <strong>pair</strong> template combines these two types and is typedefed to produce the <strong>Sighting</strong> type. Then an <strong>ostream operator&lt;&lt;</strong> is created for <strong>Sighting</strong>; this will allow you to iterate through a <strong>map</strong> or <strong>multimap</strong> of <strong>Sighting</strong>s and print it out.</p><p><strong>SightingGen</strong> generates random sightings at random data points to use for testing. It has the usual <strong>operator( )</strong> necessary for a function object, but it also has a constructor to capture and store a reference to a <strong>vector&lt;string&gt;</strong>, which is where the aforementioned animal names are stored.</p><p>A <strong>DataMap</strong> is a <strong>multimap</strong> of <strong>string</strong>-<strong>DataPoint</strong> pairs, which means it stores <strong>Sighting</strong>s. It is filled with 50 <strong>Sighting</strong>s using <strong>generate_n( )</strong> and printed out. (Notice that because there is an <strong>operator&lt;&lt;</strong> that takes a <strong>Sighting</strong>, an <strong>ostream_iterator</strong> can be created.) At this point the user is asked to select the animal for which they want to see all the sightings . If you press <strong>q,</strong> the program will quit, but if you select an animal number, the <strong>equal_range( )</strong> member function is invoked. This returns an iterator (<strong>DMIter</strong>) to the beginning of the set of matching pairs and an iterator indicating past-the-end of the set. Since only one object can be returned from a function, <strong>equal_range( )</strong> makes use of <strong>pair</strong>. Since the <strong>range</strong> pair has the beginning and ending iterators of the matching set, those iterators can be used in <strong>copy( )</strong> to print out all the sightings for a particular type of animal.</p></section><section><title><p>Multisets</p></title><p>You’ve seen the <strong>set</strong>, which allows only one object of each value to be inserted. The <strong>multiset</strong> is odd by comparison since it allows more than one object of each value to be inserted. This seems to go against the whole idea of "setness," in which you can ask, "Is ‘it’ in this set?" If there can be more than one "it," what does that question mean?<sup>.</sup></p><p>With some thought, you can see that it makes little sense to have more than one object of the same value in a set if those duplicate objects are <emphasis>exactly</emphasis> the same (with the possible exception of counting occurrences of objects, but as seen earlier in this chapter that can be handled in an alternative, more elegant fashion). Thus, each duplicate object will have something that makes it "different" from the other duplicates—most likely different state information that is not used in the calculation of the key during the comparison. That is, to the comparison operation, the objects look the same, but they actually contain some differing internal state.</p><p>Like any STL container that must order its elements, the <strong>multiset</strong> template uses the <strong>less</strong> template by default to determine element ordering. This uses the contained classes’ <strong>operator&lt;</strong>, but you can of course substitute your own comparison function.</p><p>Consider a simple class that contains one element that is used in the comparison and another that is not:</p><p>//: C07:MultiSet1.cpp</p><p>// Demonstration of multiset behavior</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;set&gt;</p><p>using namespace std;</p><empty-line/><p>class X {</p><p>  char c; // Used in comparison</p><p>  int i; // Not used in comparison</p><p>  // Don't need default constructor and operator=</p><p>  X();</p><p>  X&amp; operator=(const X&amp;);</p><p>  // Usually need a copy-constructor (but the</p><p>  // synthesized version works here)</p><p>public:</p><p>  X(char cc, int ii) : c(cc), i(ii) {}</p><p>  // Notice no operator== is required</p><p>  friend bool operator&lt;(const X&amp; x, const X&amp; y) {</p><p>    return x.c &lt; y.c;</p><p>  }</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, X x) {</p><p>    return os &lt;&lt; x.c &lt;&lt; ":" &lt;&lt; x.i;</p><p>  }</p><p>};</p><empty-line/><p>class Xgen {</p><p>  static int i;</p><p>  // Number of characters to select from:</p><p>  enum { span = 6 };</p><p>public:</p><p>  Xgen() { srand(time(0)); }</p><p>  X operator()() {</p><p>    char c = 'A' + rand() % span;</p><p>    return X(c, i++);</p><p>  }</p><p>};</p><empty-line/><p>int Xgen::i = 0;</p><empty-line/><p>typedef multiset&lt;X&gt; Xmset;</p><p>typedef Xmset::const_iterator Xmit;</p><empty-line/><p>int main() {</p><p>  Xmset mset;</p><p>  // Fill it with X's:</p><p>  generate_n(inserter(mset, mset.begin()),</p><p>    25, Xgen());</p><p>  // Initialize a regular set from mset:</p><p>  set&lt;X&gt; unique(mset.begin(), mset.end());</p><p>  copy(unique.begin(), unique.end(),</p><p>    ostream_iterator&lt;X&gt;(cout, " "));</p><p>  cout &lt;&lt; "\n----\n";</p><p>  // Iterate over the unique values:</p><p>  for(set&lt;X&gt;::iterator i = unique.begin();</p><p>      i != unique.end(); i++) {</p><p>    pair&lt;Xmit, Xmit&gt; p = mset.equal_range(*i);</p><p>    copy(p.first, p.second,</p><p>      ostream_iterator&lt;X&gt;(cout, " "));</p><p>    cout &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>In <strong>X</strong>, all the comparisons are made with the <strong>char c</strong>. The comparison is performed with <strong>operator&lt;</strong>, which is all that is necessary for the <strong>multiset</strong>, since in this example the default <strong>less</strong> comparison object is used. The class <strong>Xgen</strong> randomly generates <strong>X</strong> objects, but the comparison value is restricted to the span from ‘<strong>A</strong>’ to ‘<strong>E</strong>’. In <strong>main( )</strong>, a <strong>multiset&lt;X&gt;</strong> is created and filled with 25 <strong>X</strong> objects using <strong>Xgen</strong>, guaranteeing that there will be duplicate keys. So that we know what the unique values are, a regular <strong>set&lt;X&gt;</strong> is created from the <strong>multiset</strong> (using the <strong>iterator, iterator</strong> constructor). These values are displayed, and then each one produces the <strong>equal_range( )</strong> in the <strong>multiset</strong> (<strong>equal_range( )</strong> has the same meaning here as it does with <strong>multimap</strong>: all the elements with matching keys). Each set of matching keys is then printed.</p><p>As a second example, a (possibly) more elegant version of <strong>WordCount.cpp</strong> can be created using <strong>multiset</strong>:</p><p>//: C07:MultiSetWordCount.cpp</p><p>// Count occurrences of words using a multiset</p><p>#include &lt;fstream&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;set&gt;</p><p>#include &lt;string&gt;</p><p>#include "../require.h"</p><p>using namespace std;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  char* fname = "MultiSetWordCount.cpp";</p><p>  if(argc &gt; 1) fname = argv[1];</p><p>  ifstream in(fname);</p><p>  assure(in, fname);</p><p>  multiset&lt;string&gt; wordmset;</p><p>  string word;</p><p>  while(in &gt;&gt; word)</p><p>    wordmset.insert(word);</p><p>  typedef multiset&lt;string&gt;::iterator MSit;</p><p>  MSit it = wordmset.begin();</p><p>  while(it != wordmset.end()) {</p><p>    pair&lt;MSit, MSit&gt; p = wordmset.equal_range(*it);</p><p>    int count = distance(p.first, p.second);</p><p>    cout &lt;&lt; *it &lt;&lt; ": " &lt;&lt; count &lt;&lt; endl;</p><p>    it = p.second; // Move to the next word</p><p>  }</p><p>} ///:~</p><empty-line/><p>The setup in <strong>main( )</strong> is identical to <strong>WordCount.cpp</strong>, but then each word is simply inserted into the <strong>multiset&lt;string&gt;</strong>. An iterator is created and initialized to the beginning of the <strong>multiset</strong>; dereferencing this iterator produces the current word. The <strong>equal_range( )</strong> member function (not generic algorithm) produces the starting and ending iterators of the word that’s currently selected, and the algorithm <strong>distance( )</strong> (defined in <strong>&lt;iterator&gt;</strong>) counts the number of elements in that range. The iterator <strong>it </strong>is then moved forward to the end of the range, which puts it at the next word. If you’re unfamiliar with the <strong>multiset,</strong> this code can seem more complex. The density of it and the lack of need for supporting classes such as <strong>Count</strong> has a lot of appeal.</p><p>In the end, is this really a "set," or should it be called something else? An alternative is the generic "bag" that is defined in some container libraries, since a bag holds anything at all without discrimination—including duplicate objects. This is close, but it doesn’t quite fit since a bag has no specification about how elements should be ordered. A <strong>multiset</strong> (which requires that all duplicate elements be adjacent to each other) is even more restrictive than the concept of a set, which could use a hashing function to order its elements, in which case they would not be in sorted order. Besides, if you wanted to store a bunch of objects without any special criteria, you’d probably just use a <strong>vector</strong>, <strong>deque,</strong> or <strong>list</strong><sup><strong>.</strong></sup></p></section></section><section><title><p>Combining STL containers</p></title><p>When using a thesaurus, you want to know all the words that are similar to a particular word. When you look up a word, then, you want a list of words as the result. Here, the "multi" containers (<strong>multimap</strong> or <strong>multiset</strong>) are not appropriate. The solution is to combine containers, which is easily done using the STL. Here, we need a tool that turns out to be a powerful general concept, which is a <strong>map</strong> of <strong>vector</strong>:</p><p>//: C07:Thesaurus.cpp</p><p>// A map of vectors</p><p>//{-msc}</p><p>//{-g++}</p><p>#include &lt;map&gt;</p><p>#include &lt;vector&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;cstdlib&gt;</p><p>using namespace std;</p><empty-line/><p>typedef map&lt;string, vector&lt;string&gt; &gt; Thesaurus;</p><p>typedef pair&lt;string, vector&lt;string&gt; &gt; TEntry;</p><p>typedef Thesaurus::iterator TIter;</p><empty-line/><p>ostream&amp; operator&lt;&lt;(ostream&amp; os,const TEntry&amp; t){</p><p>  os &lt;&lt; t.first &lt;&lt; ": ";</p><p>  copy(t.second.begin(), t.second.end(),</p><p>    ostream_iterator&lt;string&gt;(os, " "));</p><p>  return os;</p><p>}</p><empty-line/><p>// A generator for thesaurus test entries:</p><p>class ThesaurusGen {</p><p>  static const string letters;</p><p>  static int count;</p><p>public:</p><p>  int maxSize() { return letters.size(); }</p><p>  ThesaurusGen() { srand(time(0)); }</p><p>  TEntry operator()() {</p><p>    TEntry result;</p><p>    if(count &gt;= maxSize()) count = 0;</p><p>    result.first = letters[count++];</p><p>    int entries = (rand() % 5) + 2;</p><p>    for(int i = 0; i &lt; entries; i++) {</p><p>      int choice = rand() % maxSize();</p><p>      char cbuf[2] = { 0 };</p><p>      cbuf[0] = letters[choice];</p><p>      result.second.push_back(cbuf);</p><p>    }</p><p>    return result;</p><p>  }</p><p>};</p><empty-line/><p>int ThesaurusGen::count = 0;</p><p>const string ThesaurusGen::letters("ABCDEFGHIJKL"</p><p>  "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");</p><empty-line/><p>// Ask for a "word" to look up:</p><p>string menu(Thesaurus&amp; thesaurus) {</p><p>  while(true) {</p><p>    cout &lt;&lt; "Select a \"word\", 0 to quit: ";</p><p>    for(TIter it = thesaurus.begin();</p><p>      it != thesaurus.end(); it++)</p><p>      cout &lt;&lt; (*it).first &lt;&lt; ' ';</p><p>    cout &lt;&lt; endl;</p><p>    string reply;</p><p>    cin &gt;&gt; reply;</p><p>    if(reply.at(0) == '0') exit(0); // Quit</p><p>    if(thesaurus.find(reply) == thesaurus.end())</p><p>      continue; // Not in list, try again</p><p>    return reply;</p><p>  }</p><p>}</p><empty-line/><p>int main() {</p><p>  Thesaurus thesaurus;</p><p>  // Fill with 10 entries:</p><p>  generate_n(</p><p>    inserter(thesaurus, thesaurus.begin()),</p><p>    10, ThesaurusGen());</p><p>  // Print everything:</p><p>  copy(thesaurus.begin(), thesaurus.end(),</p><p>    ostream_iterator&lt;TEntry&gt;(cout, "\n"));</p><p>  // Create a list of the keys:</p><p>  string keys[10];</p><p>  int i = 0;</p><p>  for(TIter it = thesaurus.begin();</p><p>    it != thesaurus.end(); it++)</p><p>    keys[i++] = (*it).first;</p><p>  for(int count = 0; count &lt; 10; count++) {</p><p>    // Enter from the console:</p><p>    // string reply = menu(thesaurus);</p><p>    // Generate randomly</p><p>    string reply = keys[rand() % 10];</p><p>    vector&lt;string&gt;&amp; v = thesaurus[reply];</p><p>    copy(v.begin(), v.end(),</p><p>      ostream_iterator&lt;string&gt;(cout, " "));</p><p>    cout &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>A <strong>Thesaurus</strong> maps a <strong>string</strong> (the word) to a <strong>vector&lt;string&gt;</strong> (the synonyms). A <strong>TEntry </strong>is a single entry in a <strong>Thesaurus</strong>. By creating an <strong>ostream operator&lt;&lt;</strong> for a <strong>TEntry</strong>, a single entry from the <strong>Thesaurus</strong> can easily be printed (and the whole <strong>Thesaurus</strong> can easily be printed with <strong>copy( )</strong>). The <strong>ThesaurusGen</strong> creates "words" (which are just single letters) and "synonyms" for those words (which are just other randomly chosen single letters) to be used as thesaurus entries. It randomly chooses the number of synonym entries to make, but there must be at least two. All the letters are chosen by indexing into a <strong>static string</strong> that is part of <strong>ThesaurusGen</strong>.</p><p>In <strong>main( )</strong>, a <strong>Thesaurus</strong> is created, filled with 10 entries and printed using the <strong>copy( )</strong> algorithm. The <strong>menu( )</strong> function asks the user to choose a "word" to look up by typing the letter of that word. The <strong>find( )</strong> member function discovers whether the entry exists in the <strong>map.</strong> (Remember, you don’t want to use <strong>operator[ ],</strong> which will automatically make a new entry if it doesn’t find a match!) If so, <strong>operator[ ]</strong> fetches out the <strong>vector&lt;string&gt;</strong> that is displayed.</p><p>In the previous code, the selection of the <strong>reply</strong> string is generated randomly, to allow automated testing.</p><p>Because templates make the expression of powerful concepts easy, you can take this concept much further, creating a <strong>map</strong> of <strong>vector</strong>s containing <strong>map</strong>s, and so on. For that matter, you can combine any of the STL containers this way.</p></section><section><title><p>Cleaning up containers of pointers</p></title><p>In <strong>Stlshape.cpp</strong>, the pointers did not clean themselves up automatically. It would be convenient to be able to do this easily, rather than writing out the code each time. Here is a function template that will clean up the pointers in any sequence container; note that it is placed in the book’s root directory for easy access:</p><p>//: :purge.h</p><p>// Delete pointers in an STL sequence container</p><p>#ifndef PURGE_H</p><p>#define PURGE_H</p><p>#include &lt;algorithm&gt;</p><empty-line/><p>template&lt;class Seq&gt; void purge(Seq&amp; c) {</p><p>  typename Seq::iterator i;</p><p>  for(i = c.begin(); i != c.end(); ++i) {</p><p>    delete *i;</p><p>    *i = 0;</p><p>  }</p><p>}</p><empty-line/><p>// Iterator version:</p><p>template&lt;class InpIt&gt;</p><p>void purge(InpIt begin, InpIt end) {</p><p>  while(begin != end) {</p><p>    delete *begin;</p><p>    *begin = 0;</p><p>    begin++;</p><p>  }</p><p>}</p><p>#endif // PURGE_H ///:~</p><empty-line/><p>In the first version of <strong>purge( )</strong>, note that <strong>typename</strong> is absolutely necessary; indeed this is exactly the case that the keyword was added for: <strong>Seq</strong> is a template argument, and <strong>iterator</strong> is something that is nested within that template. So what does <strong>Seq::iterator</strong> refer to? The <strong>typename</strong> keyword specifies that it refers to a type, and not something else.</p><p>Although the container version of <strong>purge( )</strong> must work with an STL-style container, the iterator version of <strong>purge( )</strong> will work with any range, including an array.</p><p>Here is <strong>Stlshape.cpp</strong>, modified to use the <strong>purge( )</strong> function:</p><p>//: C07:Stlshape2.cpp</p><p>// Stlshape.cpp with the purge() function</p><p>#include &lt;iostream&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../purge.h"</p><p>using namespace std;</p><empty-line/><p>class Shape {</p><p>public:</p><p>  virtual void draw() = 0;</p><p>  virtual ~Shape() {};</p><p>};</p><empty-line/><p>class Circle : public Shape {</p><p>public:</p><p>  void draw() { cout &lt;&lt; "Circle::draw\n"; }</p><p>  ~Circle() { cout &lt;&lt; "~Circle\n"; }</p><p>};</p><empty-line/><p>class Triangle : public Shape {</p><p>public:</p><p>  void draw() { cout &lt;&lt; "Triangle::draw\n"; }</p><p>  ~Triangle() { cout &lt;&lt; "~Triangle\n"; }</p><p>};</p><empty-line/><p>class Square : public Shape {</p><p>public:</p><p>  void draw() { cout &lt;&lt; "Square::draw\n"; }</p><p>  ~Square() { cout &lt;&lt; "~Square\n"; }</p><p>};</p><empty-line/><p>typedef std::vector&lt;Shape*&gt; Container;</p><p>typedef Container::iterator Iter;</p><empty-line/><p>int main() {</p><p>  Container shapes;</p><p>  shapes.push_back(new Circle);</p><p>  shapes.push_back(new Square);</p><p>  shapes.push_back(new Triangle);</p><p>  for(Iter i = shapes.begin();</p><p>      i != shapes.end(); i++)</p><p>    (*i)-&gt;draw();</p><p>  purge(shapes);</p><p>} ///:~</p><empty-line/><p>When using <strong>purge( )</strong>, carefully consider ownership issues. If an object pointer is held in more than one container, be sure not to delete it twice, and you don’t want to destroy the object in the first container before the second one is finished with it. Purging the same container twice is not a problem, because <strong>purge( )</strong> sets the pointer to zero once it deletes that pointer, and calling <strong>delete</strong> for a zero pointer is a safe operation.</p></section><section><title><p>Creating your own containers</p></title><p>With the STL as a foundation, you can create your own containers. Assuming you follow the same model of providing iterators, your new container will behave as if it were a built-in STL container.</p><p>Consider the "ring" data structure, which is a circular sequence container. If you reach the end, it just wraps around to the beginning. This can be implemented on top of a <strong>list</strong> as follows:</p><p>//: C07:Ring.cpp</p><p>// Making a "ring" data structure from the STL</p><p>#include &lt;iostream&gt;</p><p>#include &lt;list&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T&gt;</p><p>class Ring {</p><p>  list&lt;T&gt; lst;</p><p>public:</p><p>  // Declaration necessary so the following</p><p>  // 'friend' statement sees this 'iterator'</p><p>  // instead of std::iterator:</p><p>  class iterator;</p><p>  friend class iterator;</p><p>  class iterator : public std::iterator&lt;</p><p>    std::bidirectional_iterator_tag,T,ptrdiff_t&gt;{</p><p>    typename list&lt;T&gt;::iterator it;</p><p>    list&lt;T&gt;* r;</p><p>  public:</p><p>    iterator(list&lt;T&gt;&amp; lst,</p><p>      const typename list&lt;T&gt;::iterator&amp; i)</p><p>      : r(&amp;lst), it(i) {}</p><p>    bool operator==(const iterator&amp; x) const {</p><p>      return it == x.it;</p><p>    }</p><p>    bool operator!=(const iterator&amp; x) const {</p><p>      return !(*this == x);</p><p>    }</p><p>    typename list&lt;T&gt;::reference operator*() const {</p><p>      return *it;</p><p>    }</p><p>    iterator&amp; operator++() {</p><p>      ++it;</p><p>      if(it == r-&gt;end())</p><p>        it = r-&gt;begin();</p><p>      return *this;</p><p>    }</p><p>    iterator operator++(int) {</p><p>      iterator tmp = *this;</p><p>      ++*this;</p><p>      return tmp;</p><p>    }</p><p>    iterator&amp; operator--() {</p><p>      if(it == r-&gt;begin())</p><p>        it = r-&gt;end();</p><p>      --it;</p><p>      return *this;</p><p>    }</p><p>    iterator operator--(int) {</p><p>      iterator tmp = *this;</p><p>      --*this;</p><p>      return tmp;</p><p>    }</p><p>    iterator insert(const T&amp; x){</p><p>      return iterator(*r, r-&gt;insert(it, x));</p><p>    }</p><p>    iterator erase() {</p><p>      return iterator(*r, r-&gt;erase(it));</p><p>    }</p><p>  };</p><p>  void push_back(const T&amp; x) {</p><p>    lst.push_back(x);</p><p>  }</p><p>  iterator begin() {</p><p>    return iterator(lst, lst.begin());</p><p>  }</p><p> int size() { return lst.size(); }</p><p>};</p><empty-line/><p>int main() {</p><p>  Ring&lt;string&gt; rs;</p><p>  rs.push_back("one");</p><p>  rs.push_back("two");</p><p>  rs.push_back("three");</p><p>  rs.push_back("four");</p><p>  rs.push_back("five");</p><p>  Ring&lt;string&gt;::iterator it = rs.begin();</p><p>  it++; it++;</p><p>  it.insert("six");</p><p>  it = rs.begin();</p><p>  // Twice around the ring:</p><p>  for(int i = 0; i &lt; rs.size() * 2; i++)</p><p>    cout &lt;&lt; *it++ &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>You can see that most of the coding is in the iterator. The <strong>Ring iterator</strong> must know how to loop back to the beginning, so it must keep a reference to the <strong>list </strong>of its "parent" <strong>Ring</strong> object in order to know if it’s at the end and how to get back to the beginning.</p><p>You’ll notice that the interface for <strong>Ring</strong> is quite limited; in particular, there is no <strong>end( )</strong>, since a ring just keeps looping. This means that you won’t be able to use a <strong>Ring</strong> in any STL algorithms that require a past-the-end iterator, which is many of them. (It turns out that adding this feature is a nontrivial exercise.) Although this can seem limiting, consider <strong>stack</strong>, <strong>queue,</strong> and <strong>priority_queue</strong>, which don’t produce any iterators at all!<sup>.</sup></p></section><section><title><p>STL extensions</p></title><p>Although the STL containers may provide all the functionality you’ll ever need, they are not complete. For example, the standard implementations of <strong>set</strong> and <strong>map</strong> use trees, and although these are reasonably fast, they may not be fast enough for your needs. In the C++ Standards Committee it was generally agreed that hashed implementations of <strong>set</strong> and <strong>map</strong> should have been included in Standard C++; however, there was not enough time to add these components, and thus they were left out.<a l:href="#n101" type="note">[101]</a></p><p>Fortunately, alternatives are freely available. One of the nice things about the STL is that it establishes a basic model for creating STL-like classes, so anything built using the same model is easy to understand if you are already familiar with the STL.</p><p>The SGI STL from Silicon Graphics<a l:href="#n102" type="note">[102]</a> is one of the most robust implementations of the STL and can be used to replace your compiler’s STL if that is found wanting. In addition, SGI has added a number of extensions including <strong>hash_set</strong>, <strong>hash_multiset</strong>, <strong>hash_map</strong>, <strong>hash_multimap</strong>, <strong>slist</strong> (a singly linked list), and <strong>rope</strong> (a variant of <strong>string</strong> optimized for very large strings and fast concatenation and substring operations).</p><p>Let’s consider a performance comparison between a tree-based <strong>map</strong> and the SGI <strong>hash_map</strong>. To keep things simple, the mappings will be from <strong>int</strong> to <strong>int</strong>:</p><p>//: C07:MapVsHashMap.cpp</p><p>// The hash_map header is not part of the</p><p>// Standard C++ STL. It is an extension that</p><p>// is only available as part of the SGI STL</p><p>// (Included with the g++ distribution)</p><p>//{-bor} You can add the header by hand</p><p>//{-msc} You can add the header by hand</p><p>//{-g++} You can add the header by hand</p><p>#include &lt;hash_map&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;map&gt;</p><p>#include &lt;ctime&gt;</p><p>using namespace std;</p><empty-line/><p>int main(){</p><p>  hash_map&lt;int, int&gt; hm;</p><p>  map&lt;int, int&gt; m;</p><p>  clock_t ticks = clock();</p><p>  for(int i = 0; i &lt; 100; i++)</p><p>    for(int j = 0; j &lt; 1000; j++)</p><p>      m.insert(make_pair(j,j));</p><p>  cout &lt;&lt; "map insertions: "</p><p>    &lt;&lt; clock() - ticks &lt;&lt; endl;</p><p>  ticks = clock();</p><p>  for(int i = 0; i &lt; 100; i++)</p><p>    for(int j = 0; j &lt; 1000; j++)</p><p>      hm.insert(make_pair(j,j));</p><p>  cout &lt;&lt; "hash_map insertions: "</p><p>    &lt;&lt; clock() - ticks &lt;&lt; endl;</p><p>  ticks = clock();</p><p>  for(int i = 0; i &lt; 100; i++)</p><p>    for(int j = 0; j &lt; 1000; j++)</p><p>      m[j];</p><p>  cout &lt;&lt; "map::operator[] lookups: "</p><p>    &lt;&lt; clock() - ticks &lt;&lt; endl;</p><p>  ticks = clock();</p><p>  for(int i = 0; i &lt; 100; i++)</p><p>    for(int j = 0; j &lt; 1000; j++)</p><p>      hm[j];</p><p>  cout &lt;&lt; "hash_map::operator[] lookups: "</p><p>    &lt;&lt; clock() - ticks &lt;&lt; endl;</p><p>  ticks = clock();</p><p>  for(int i = 0; i &lt; 100; i++)</p><p>    for(int j = 0; j &lt; 1000; j++)</p><p>      m.find(j);</p><p>  cout &lt;&lt; "map::find() lookups: "</p><p>    &lt;&lt; clock() - ticks &lt;&lt; endl;</p><p>  ticks = clock();</p><p>  for(int i = 0; i &lt; 100; i++)</p><p>    for(int j = 0; j &lt; 1000; j++)</p><p>      hm.find(j);</p><p>  cout &lt;&lt; "hash_map::find() lookups: "</p><p>    &lt;&lt; clock() - ticks &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The performance test we ran showed a speed improvement of roughly 4:1 for the <strong>hash_map</strong> over the <strong>map</strong> in all operations (and as expected, <strong>find( )</strong> is slightly faster than <strong>operator[ ]</strong> for lookups for both types of map). If a profiler shows a bottleneck in your <strong>map</strong>, consider a <strong>hash_map</strong>.</p></section><section><title><p>Non-STL containers</p></title><p>There are two "non-STL" containers in the standard library: <strong>bitset</strong> and <strong>valarray</strong>.<a l:href="#n103" type="note">[103]</a> We say "non-STL" because neither of these containers fulfills all the requirements of STL containers. The <strong>bitset</strong> container, which we covered earlier in this chapter, packs bits into integers and does not allow direct addressing of its members. The <strong>valarray</strong> template class is a vector-like container that is optimized for efficient numeric computation. Neither container provides iterators. Although you can instantiate a <strong>valarray</strong> with nonnumeric types, it has mathematical functions that are intended to operate with numeric data, such as <strong>sin</strong>, <strong>cos</strong>, <strong>tan</strong>, and so on. Most of <strong>valarray</strong>’s functions and operators operate on a <strong>valarray</strong> as a whole, as the following example illustrates.</p><p>//: C07:Valarray1.cpp</p><p>//{-bor}</p><p>// Illustrates basic valarray functionality</p><p>#include &lt;iostream&gt;</p><p>#include &lt;valarray&gt;</p><p>using namespace std;</p><empty-line/><p>double f(double x) {</p><p>  return 2.0 * x - 1.0;</p><p>}</p><empty-line/><p>template&lt;class T&gt;</p><p>void print(const char* lbl, const valarray&lt;T&gt;&amp; a) {</p><p>  cout &lt;&lt; lbl &lt;&lt; ": ";</p><p>  for(size_t i = 0; i &lt; a.size(); ++i)</p><p>    cout &lt;&lt; a[i] &lt;&lt; ' ';</p><p>  cout &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main() {</p><p>  double n[] = {1.0, 2.0, 3.0, 4.0};</p><p>  valarray&lt;double&gt; v(n, sizeof n / sizeof n[0]);</p><p>  print("v", v);</p><p>  valarray&lt;double&gt; sh(v.shift(1));</p><p>  print("shift 1", sh);</p><p>  valarray&lt;double&gt; acc(v + sh);</p><p>  print("sum", acc);</p><p>  valarray&lt;double&gt; trig(sin(v) + cos(acc));</p><p>  print("trig", trig);</p><p>  valarray&lt;double&gt; p(pow(v, 3.0));</p><p>  print("3rd power", p);</p><p>  valarray&lt;double&gt; app(v.apply(f));</p><p>  print("f(v)", app);</p><p>  valarray&lt;bool&gt; eq(v == app);</p><p>  print("v == app?", eq);</p><p>  double x = v.min();</p><p>  double y = v.max();</p><p>  double z = v.sum();</p><p>  cout &lt;&lt; "x = " &lt;&lt; x &lt;&lt; ", y = " &lt;&lt; y</p><p>    &lt;&lt; ", z = " &lt;&lt; z  &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The <strong>valarray</strong> class provides a constructor that takes an array of the target type and the count of elements in the array to be used to initialize the new <strong>valarray</strong>. The <strong>shift( )</strong> member function shifts each <strong>valarray</strong> element one position to the left (or to the right, if its argument is negative) and fills in holes with the default value for the type (zero in this case). There is also a <strong>cshift( )</strong> member function that does a circular shift (or "rotate"). All mathematical operators and functions are overloaded to operate on <strong>valarray</strong>s, and binary operators require <strong>valarray</strong> arguments of the same type and size. The <strong>apply( )</strong> member function, like the <strong>transform( )</strong> algorithm, applies a function to each element, but the result is collected into a result <strong>valarray</strong>. The relational operators return suitably sized instances of <strong>valarray&lt;bool&gt;</strong> that indicate the result of element-by-element comparisons, such as with <strong>eq</strong> above. Most operations return a new result array, but a few, such as <strong>min( )</strong>, <strong>max( )</strong>, and <strong>sum( )</strong>, return a single scalar value for obvious reasons.</p><p>The most interesting thing you can do with <strong>valarray</strong>s is reference subsets of their elements, not only for extracting information, but for updating it. A subset of a <strong>valarray</strong> is called a <emphasis>slice</emphasis>, and certain operators use slices to do their work. The following sample program uses slices.</p><p>//: C07:Valarray2.cpp</p><p>// Illustrates slices and masks</p><p>//{-bor}</p><p>#include &lt;valarray&gt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T&gt;</p><p>void print(const char* lbl, const valarray&lt;T&gt;&amp; a) {</p><p>  cout &lt;&lt; lbl &lt;&lt; ": ";</p><p>  for(size_t i = 0; i &lt; a.size(); ++i)</p><p>    cout &lt;&lt; a[i] &lt;&lt; ' ';</p><p>  cout &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main() {</p><p>  int data[] = {1,2,3,4,5,6,7,8,9,10,11,12};</p><p>  valarray&lt;int&gt; v(data, 12);</p><p>  valarray&lt;int&gt; r1(v[slice(0, 4, 3)]);</p><p>  print("slice(0,4,3)", r1);</p><p>  // Extract conditionally</p><p>  valarray&lt;int&gt; r2(v[v &gt; 6]);</p><p>  print("elements &gt; 6", r2);</p><p>  // Square first column</p><p>  v[slice(0, 4, 3)] *= valarray&lt;int&gt;(v[slice(0, 4, 3)]);</p><p>  print("after squaring first column", v);</p><p>  // Restore it</p><p>  int idx[] = {1,4,7,10};</p><p>  valarray&lt;int&gt; save(idx, 4);</p><p>  v[slice(0, 4, 3)] = save;</p><p>  print("v restored", v);</p><p>  // Extract a 2-d subset: {{1, 3, 5}, {7, 9, 11}}</p><p>  valarray&lt;size_t&gt; siz(2);</p><p>  siz[0] = 2;</p><p>  siz[1] = 3;</p><p>  valarray&lt;size_t&gt; gap(2);</p><p>  gap[0] = 6;</p><p>  gap[1] = 2;</p><p>  valarray&lt;int&gt; r3(v[gslice(0, siz, gap)]);</p><p>  print("2-d slice", r3);</p><p>  // Extract a subset via a boolean mask (bool elements)</p><p>  valarray&lt;bool&gt; mask(false, 5);</p><p>  mask[1] = mask[2] = mask[4] = true;</p><p>  valarray&lt;int&gt; r4(v[mask]);</p><p>  print("v[mask]", r4);</p><p>  // Extract a subset via an index mask (size_t elements)</p><p>  size_t idx2[] = {2,2,3,6};</p><p>  valarray&lt;size_t&gt; mask2(idx2, 4);</p><p>  valarray&lt;int&gt; r5(v[mask2]);</p><p>  print("v[mask2]", r5);</p><p>  // Use an index mask in assignment</p><p>  valarray&lt;char&gt; text("now is the time", 15);</p><p>  valarray&lt;char&gt; caps("NITT", 4);</p><p>  valarray&lt;size_t&gt; idx3(4);</p><p>  idx3[0] = 0;</p><p>  idx3[1] = 4;</p><p>  idx3[2] = 7;</p><p>  idx3[3] = 11;</p><p>  text[idx3] = caps;</p><p>  print("capitalized", text);</p><p>} ///:~</p><empty-line/><p>A <strong>slice</strong> object takes three arguments: the starting index, the number of elements to extract, and the "stride," which is the gap between elements of interest. Slices can be used as indexes into an existing <strong>valarray</strong>, and a new <strong>valarray</strong> containing the extracted elements is returned. A <strong>valarray</strong> of <strong>bool</strong>, such as is returned by the expression <strong>v &gt; 6</strong>, can be used as an index into another <strong>valarray</strong>; the elements corresponding to the <strong>true</strong> slots are extracted. As you can see, you can also use slices and masks as indexes on the left side of an assignment. A <strong>gslice</strong> object (for "generalized slice") is like a slice, except that the counts and strides are themselves arrays, which allows you to interpret a <strong>valarray</strong> as a multidimensional array. The example above extracts a 2 by 3 array from <strong>v</strong>, where the numbers start at zero and the numbers for the first dimension are found six slots apart in <strong>v</strong>, and the others two apart, which effectively extracts the matrix</p><p>1 3 5</p><p>7 9 11</p><empty-line/><p>Here is the complete output for this program:</p><p>slice(0,4,3): 1 4 7 10</p><p>elements &gt; 6: 7 8 9 10</p><p>after squaring v: 1 2 3 16 5 6 49 8 9 100 11 12</p><p>v restored: 1 2 3 4 5 6 7 8 9 10 11 12</p><p>2-d slice: 1 3 5 7 9 11</p><p>v[mask]: 2 3 5</p><p>v[mask2]: 3 3 4 7</p><p>capitalized: N o w   I s   T h e   T i m e</p><empty-line/><p>A practical example of slices is found in matrix multiplication. Consider how you would write a function to multiply two matrices of integers with arrays.</p><p>void matmult(const int a[][MAXCOLS], size_t m, size_t n,</p><p>             const int b[][MAXCOLS], size_t p, size_t q,</p><p>             int result[][MAXCOLS);</p><empty-line/><p>This function multiplies the <strong>m</strong>-by-<strong>n</strong> matrix <strong>a</strong> by the <strong>p</strong>-by-<strong>q</strong> matrix <strong>b</strong>, where <strong>n</strong> and <strong>p</strong> are equal, of course. As you can see, without something like <strong>valarray</strong>, you need to fix the maximum value for the second dimension of each matrix, since locations in arrays are statically determined. It is also difficult to return a result array by value, so the caller usually passes the result array as an argument.</p><p>Using <strong>valarray</strong> not only allows you to pass any size matrix, but you can also easily process matrices of any type, and return the result by value. Here’s how:</p><p>// Multiplies compatible matrices in valarrays</p><p>template&lt;class T&gt;</p><p>valarray&lt;T&gt; matmult(const valarray&lt;T&gt;&amp; a, size_t arows,</p><p>     size_t acols, const valarray&lt;T&gt;&amp; b,</p><p>     size_t brows, size_t bcols) {</p><p>  assert(acols == brows);</p><p>  valarray&lt;T&gt; result(arows * bcols);</p><p>  for(size_t i = 0; i &lt; arows; ++i)</p><p>    for(size_t j = 0; j &lt; bcols; ++j) {</p><p>      // Take dot product of row a[i] and col b[j]</p><p>      valarray&lt;T&gt; row = a[slice(acols*i, acols, 1)];</p><p>      valarray&lt;T&gt; col = b[slice(j, brows, bcols)];</p><p>      result[i*bcols + j] = (row * col).sum();</p><p>    }</p><p>  return result;</p><p>}</p><empty-line/><p>Each entry in the result matrix is the dot product of a row in <strong>a</strong> with a column in <strong>b</strong>. By taking slices, you can extract these rows and columns as <strong>valarray</strong>s and use the global <strong>*</strong> operator and <strong>sum( )</strong> function provided by <strong>valarray</strong> to do the work succinctly. The result <strong>valarray</strong> is computed at runtime; there’s no need to worry about the static limitations of array dimensions. You do have to compute linear offsets of the position <strong>[i][j]</strong> yourself (see the formula <strong>i*bcols + j</strong> above), but the size and type freedom is worth it<sup>.</sup></p></section><section><title><p>Summary</p></title><p>The goal of this chapter was not just to introduce the STL containers in some considerable depth. (Of course, not every detail could be covered here, but you have enough now that you can look up further information in the other resources.) Our higher hope is that this chapter has made you grasp the incredible power available in the STL and shown you how much faster and more efficient your programming activities can be by using and understanding the STL.</p></section><section><title><p>Exercises</p></title><p>             1.             Create a <strong>set&lt;char&gt;</strong>, open a file (whose name is provided on the command line), and read that file in a <strong>char</strong> at a time, placing each <strong>char</strong> in the set. Print the results, and observe the organization. Are there any letters in the alphabet that are not used in that particular file?</p><p>        39.             Create three sequences of <strong>Noisy</strong> objects, a <strong>vector</strong>, <strong>deque</strong>, and <strong>list</strong>. Sort them. Now write a function template to receive the <strong>vector</strong> and <strong>deque</strong> sequences as a parameter to sort them and record the sorting time. Write a specialized template function to do the same for <strong>list</strong> (ensure to call its member <strong>sort( )</strong> instead of the generic algorithm). Compare the performance of the different sequence types.</p><p>        40.             Write a program to compare the speed of sorting a list using <strong>list::sort( )</strong> vs. using <strong>std::sort( )</strong> (the STL algorithm version of <strong>sort( )</strong>).</p><p>         41.             Create a generator that produces random <strong>int</strong> values between 0 and 20 inclusive, and use it to fill a <strong>multiset&lt;int&gt;</strong>. Count the occurrences of each value, following the example given in <strong>MultiSetWordCount.cpp</strong>.</p><p>        42.             Change <strong>StlShape.cpp</strong> so that it uses a <strong>deque</strong> instead of a <strong>vector</strong>.</p><p>        43.             Modify <strong>Reversible.cpp</strong> so it works with <strong>deque</strong> and <strong>list</strong> instead of <strong>vector</strong>.</p><p>        44.             Use a <strong>stack&lt;int&gt;</strong> and populate it with a Fibonacci sequence. The program’s command line should take the number of Fibonacci elements desired, and you should have a loop that looks at the last two elements on the stack and pushes a new one for every pass through the loop.</p><p>        45.             Using only three <strong>stack</strong>s (<emphasis>source</emphasis>, <emphasis>sorted</emphasis>, and <emphasis>losers</emphasis>), sort a random sequence of numbers by placing the numbers initially on the <emphasis>source</emphasis> stack. Assume the number on the top of the <emphasis>source</emphasis> is the largest, and push it on the <emphasis>sorted</emphasis> stack. Continue to pop the <emphasis>source</emphasis> stack comparing it with the top of the <emphasis>sorted</emphasis> stack. Whichever number is the smallest, pop it from its stack and push it onto the on the <emphasis>losers’</emphasis> stack. Once the <emphasis>source</emphasis> stack is empty, repeat the process using the <emphasis>loser’s</emphasis> stack as the <emphasis>source</emphasis> stack, and use the <emphasis>source</emphasis> stack as the <emphasis>losers’</emphasis> stack. The algorithm completes when all the numbers have been placed into the <emphasis>winners’</emphasis> stack.</p><p>        46.             Open a text file whose name is provided on the command line. Read the file a word at a time, and use a <strong>multiset&lt;string&gt;</strong> to create a word count for each word.</p><p>         47.             Modify <strong>WordCount.cpp</strong> so that it uses <strong>insert( )</strong> instead of <strong>operator[ ]</strong> to insert elements in the map.</p><p>        48.             Create a class that has an <strong>operator&lt;</strong> and an <strong>ostream&amp; operator&lt;&lt;</strong>. The class should contain a priority number. Create a generator for your class that makes a random priority number. Fill a <strong>priority_queue</strong> using your generator, and then pull the elements out to show they are in the proper order.</p><p>        49.             Rewrite <strong>Ring.cpp</strong> so it uses a <strong>deque</strong> instead of a <strong>list</strong> for its underlying implementation.</p><p>        50.             Modify <strong>Ring.cpp</strong> so that the underlying implementation can be chosen using a template argument. (Let that template argument default to <strong>list</strong>.)</p><p>         51.             Create an iterator class called <strong>BitBucket</strong> that just absorbs whatever you send to it without writing it anywhere.</p><p>        52.             Create a kind of "hangman" game. Create a class that contains a <strong>char</strong> and a <strong>bool</strong> to indicate whether that <strong>char</strong> has been guessed yet. Randomly select a word from a file, and read it into a vector of your new type. Repeatedly ask the user for a character guess, and after each guess, display the characters in the word that have been guessed, and display underscores for the characters that haven’t. Allow a way for the user to guess the whole word. Decrement a value for each guess, and if the user can get the whole word before the value goes to zero, they win.</p><p>        53.             Open a file and read it into a single string. Turn the string into a <strong>stringstream</strong>. Read tokens from the <strong>stringstream</strong> into a <strong>list&lt;string&gt;</strong> using a <strong>TokenIterator</strong>.</p><p>        54.             Compare the performance of <strong>stack</strong> based on whether it is implemented with <strong>vector</strong>, <strong>deque</strong>, or <strong>list</strong>.</p><p>        55.             Create a template that implements a singly-linked list called <strong>SList</strong>. Provide a default constructor and <strong>begin( )</strong> and <strong>end( )</strong> functions (via an appropriate nested iterator), <strong>insert( )</strong>, <strong>erase( )</strong> and a destructor.</p><p>        56.             Generate a sequence of random integers storing them into an array of <strong>int</strong>. Initialize a <strong>valarray&lt;int&gt;</strong> with its contents. Compute the sum, minimum value, maximum value, average, and median of the integers using <strong>valarray</strong> operations.</p><p>         57.             Create a <strong>valarray&lt;int&gt;</strong> with 12 random values. Create another <strong>valarray&lt;int&gt;</strong> with 20 random values. You will interpret the first <strong>valarray</strong> as a 3 x 4 matrix of <strong>int</strong>s and the second as a 4 x 5 matrix of <strong>int</strong>s, and multiply them by the rules of matrix multiplication. Store the result in a <strong>valarray&lt;int&gt;</strong> of size 15, representing the 3 x 5 result matrix. Use slices to multiply the rows of the first matrix time the columns of the second. Print the result in rectangular matrix form.</p><p>[ ]</p></section></section></section><section><title><p>Part 3: Special Topics</p></title><section><p>The mark of a professional in any field appears in his or her attention to the finer points of the craft. In this part of the book we discuss advanced features of C++ along with development techniques used by polished C++ professionals.</p><p>Once in a great while you may need to depart from the conventional wisdom of sound object-oriented design by inspecting the runtime type of an object for special processing. Most of the time you should let virtual functions do that job for you, but when writing special-purpose software tools, such as debuggers, database viewers, or class browsers, you’ll need to determine type information at runtime. This is where the runtime type identification (RTTI) mechanism comes into play, which is the topic of Chapter 8. Multiple inheritance has taken a bad rap over the years, and some languages don’t even support it. Nonetheless, when used properly, it can be a powerful tool for crafting elegant, efficient code. A number of standard practices involving multiple inheritance have evolved over the years, which we present in Chapter 9. Perhaps the most notable innovation in software development since object-oriented techniques is the use of design patterns. A design pattern describes and presents solutions for many of the common problems involved in designing software, and can be applied in many situations and implemented in any language. In chapter 10 we describe a selected number of widely-used design patterns and implement them in C++. Chapter 11 explains in detail the benefits and challenges of multi-threaded programming. The current version of standard C++ does not specify support for threads, even though most operating systems support them. We use a portable, freely-available thread library to illustrate how C++ programmers can take advantage of threads to build more usable and responsive applications.</p></section><section><title><p>8: Runtime type identification</p></title><section><p>Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type.</p><p>This can be thought of as a "secondary" feature in C++, pragmatism to help out when you get into rare messy situations. Normally, you’ll want to intentionally ignore the exact type of an object and let the virtual function mechanism implement the correct behavior for that type automatically. On occasion, however, it’s useful to know the exact <emphasis>runtime</emphasis> (that is, most derived) type of an object for which you only have a base pointer. Often this information allows you to perform a special-case operation more efficiently or prevent a base-class interface from becoming ungainly. It happens enough that most class libraries contain virtual functions to produce run-time type information. When exception handling was added to C++, it required information about the runtime type of objects. It became an easy next step to build access to that information into the language. This chapter explains what RTTI is for and how to use it<sup>.</sup></p></section><section><title><p>Runtime casts</p></title><p>One way to determine the runtime type of an object through a pointer is to employ a <emphasis>runtime cast</emphasis>, which verifies that the attempted conversion is valid. This is useful when you need to cast a base-class pointer to a derived type. Since inheritance hierarchies are typically depicted with base classes above derived classes, such a cast is called a <emphasis>downcast</emphasis>.</p><p>Consider the following class hierarchy.</p><p><image l:href="#6"/></p><empty-line/><p>In the code that follows, the <strong>Investment</strong> class has an extra operation that the other classes do not, so it is important to be able to know at runtime whether a <strong>Security</strong> pointer refers to a <strong>Investment</strong> object or not. To implement checked runtime casts, each class keeps an integral identifier to distinguish it from other classes in the hierarchy<sup>.</sup></p><p>//: C08:CheckedCast.cpp</p><p>// Checks casts at runtime</p><p>#include &lt;iostream&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../purge.h"</p><p>using namespace std;</p><empty-line/><p>class Security {</p><p>protected:</p><p>  enum {BASEID = 0};</p><p>public:</p><p>  virtual ~Security() {}</p><p>  virtual bool isA(int id) {</p><p>     return (id == BASEID);</p><p>  }</p><p>};</p><p>class Stock : public Security {</p><p>  typedef Security Super;</p><p>protected:</p><p>  enum {OFFSET = 1, TYPEID = BASEID + OFFSET};</p><p>public:</p><p>  bool isA(int id) {</p><p>    return id == TYPEID || Super::isA(id);</p><p>  }</p><p>  static Stock* dynacast(Security* s) {</p><p>    return (s-&gt;isA(TYPEID)) ?</p><p>      static_cast&lt;Stock*&gt;(s) : 0;</p><p>  }</p><p>};</p><p>class Bond : public Security {</p><p>  typedef Security Super;</p><p>protected:</p><p>  enum {OFFSET = 2, TYPEID = BASEID + OFFSET};</p><p>public:</p><p>  bool isA(int id) {</p><p>    return id == TYPEID || Super::isA(id);</p><p>  }</p><p>  static Bond* dynacast(Security* s) {</p><p>    return (s-&gt;isA(TYPEID)) ?</p><p>      static_cast&lt;Bond*&gt;(s) : 0;</p><p>  }</p><p>};</p><p>class Investment : public Security {</p><p>  typedef Security Super;</p><p>protected:</p><p>  enum {OFFSET = 3, TYPEID = BASEID + OFFSET};</p><p>public:</p><p>  bool isA(int id) {</p><p>    return id == BASEID || Super::isA(id);</p><p>  }</p><p>  static Investment* dynacast(Security* s) {</p><p>    return (s-&gt;isA(TYPEID)) ?</p><p>      static_cast&lt;Investment*&gt;(s) : 0;</p><p>  }</p><p>  void special() {</p><p>    cout &lt;&lt; "special Investment function\n";</p><p>  }</p><p>};</p><empty-line/><p>class Metal : public Investment {</p><p>  typedef Investment Super;</p><p>protected:</p><p>  enum {OFFSET = 4, TYPEID = BASEID + OFFSET};</p><p>public:</p><p>  bool isA(int id) {</p><p>    return id == BASEID || Super::isA(id);</p><p>  }</p><p>  static Metal* dynacast(Security* s) {</p><p>    return (s-&gt;isA(TYPEID)) ?</p><p>      static_cast&lt;Metal*&gt;(s) : 0;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  vector&lt;Security*&gt; portfolio;</p><p>  portfolio.push_back(new Metal);</p><p>  portfolio.push_back(new Investment);</p><p>  portfolio.push_back(new Bond);</p><p>  portfolio.push_back(new Stock);</p><p>  for (vector&lt;Security*&gt;::iterator it =</p><p>         portfolio.begin();</p><p>       it != portfolio.end(); ++it) {</p><p>    Investment* cm = Investment::dynacast(*it);</p><p>    if(cm)</p><p>      cm-&gt;special();</p><p>    else</p><p>      cout &lt;&lt; "not a Investment" &lt;&lt; endl;</p><p>  }</p><p>  cout &lt;&lt; "cast from intermediate pointer:\n";</p><p>  Security* sp = new Metal;</p><p>  Investment* cp = Investment::dynacast(sp);</p><p>  if(cp) cout &lt;&lt; "  it's an Investment\n";</p><p>  Metal* mp = Metal::dynacast(sp);</p><p>  if(mp) cout &lt;&lt; "  it's a Metal too!\n";</p><p>  purge(portfolio);</p><p>} ///:~</p><empty-line/><p>The polymorphic <strong>isA( )</strong> function checks to see if its argument is compatible with its type argument (<strong>id</strong>), which means that either <strong>id</strong> matches the object’s <strong>typeID</strong> exactly or that of one of its ancestors in the hierarchy (hence the call to <strong>Super::isA( )</strong> in that case). The <strong>dynacast( )</strong> function, which is static in each class, calls <strong>isA( )</strong> for its pointer argument to check if the cast is valid. If <strong>isA( )</strong> returns <strong>true</strong>, the cast is valid, and a suitably cast pointer is returned. Otherwise, the null pointer is returned, which tells the caller that the cast is not valid, meaning that the original pointer is not pointing to an object compatible with (convertible to) the desired type. All this machinery is necessary to be able to check intermediate casts, such as from a <strong>Security</strong> pointer that refers to a <strong>Metal</strong> object to a <strong>Investment</strong> pointer in the previous example program.<a l:href="#n104" type="note">[104]</a></p><p>Although for most programs downcasting is not needed (and indeed is discouraged, since everyday polymorphism solves most problems in object-oriented application programs), the ability to check a cast to a more derived type is important for utility programs such as debuggers, class browsers, and databases. C++ provides such a checked cast with the <strong>dynamic_cast</strong> operator. The following program is a rewrite of the previous example using <strong>dynamic_cast</strong><sup><strong>.</strong></sup></p><p>//: C08:CheckedCast2.cpp</p><p>// Uses RTTI’s dynamic_cast</p><p>#include &lt;iostream&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../purge.h"</p><p>using namespace std;</p><empty-line/><p>class Security {</p><p>public:</p><p>  virtual ~Security(){}</p><p>};</p><p>class Stock : public Security {};</p><p>class Bond : public Security {};</p><p>class Investment : public Security {</p><p>public:</p><p>  void special() {</p><p>    cout &lt;&lt; "special Investment function\n";</p><p>  }</p><p>};</p><p>class Metal : public Investment {};</p><empty-line/><p>int main() {</p><p>  vector&lt;Security*&gt; portfolio;</p><p>  portfolio.push_back(new Metal);</p><p>  portfolio.push_back(new Investment);</p><p>  portfolio.push_back(new Bond);</p><p>  portfolio.push_back(new Stock);</p><p>  for (vector&lt;Security*&gt;::iterator it =</p><p>                    portfolio.begin();</p><p>       it != portfolio.end(); ++it) {</p><p>    Investment* cm = dynamic_cast&lt;Investment*&gt;(*it);</p><p>    if(cm)</p><p>      cm-&gt;special();</p><p>    else</p><p>      cout &lt;&lt; "not a Investment" &lt;&lt; endl;</p><p>  }</p><p>  cout &lt;&lt; "cast from intermediate pointer:\n";</p><p>  Security* sp = new Metal;</p><p>  Investment* cp = dynamic_cast&lt;Investment*&gt;(sp);</p><p>  if(cp) cout &lt;&lt; "  it's an Investment\n";</p><p>  Metal* mp = dynamic_cast&lt;Metal*&gt;(sp);</p><p>  if(mp) cout &lt;&lt; "  it's a Metal too!\n";</p><p>  purge(portfolio);</p><p>} ///:~</p><empty-line/><p>This example is much shorter, since most of the code in the original example was just the overhead for checking the casts. The target type of a <strong>dynamic_cast</strong> is placed in angle brackets, like the other new-style C++ casts (<strong>static_cast</strong>, and so on), and the object to cast appears as the operand. <strong>dynamic_cast</strong> requires that the types you use it with be <emphasis>polymorphic</emphasis> if you want safe downcasts.<a l:href="#n105" type="note">[105]</a> This in turn requires that the class must have at least one virtual function. Fortunately, the <strong>Security</strong> base class has a virtual destructor, so we didn’t have to invent some extraneous function to get the job done. <strong>dynamic_cast</strong> does its work at runtime, of course, since it has to check the virtual function table of objects according to there dynamic type. This naturally implies that <strong>dynamic_cast</strong> tends to be more expensive than the other new-style casts<sup>.</sup></p><p>You can also use <strong>dynamic_cast</strong> with references instead of pointers, but since there is no such thing as a null reference, you need another way to know if the cast fails. That "other way" is to catch a <strong>bad_cast</strong> exception, as follows:</p><p>  Metal m;</p><p>  Security&amp; s = m;</p><p>  try {</p><p>    Investment&amp; c = dynamic_cast&lt;Investment&amp;&gt;(s);</p><p>    cout &lt;&lt; "  it's an Investment\n";</p><p>  }</p><p>  catch (bad_cast&amp;) {</p><p>    cout &lt;&lt; "s is not an Investment type\n";</p><p>  }</p><empty-line/><p>The <strong>bad_cast</strong> class is defined in the <strong>&lt;typeinfo&gt;</strong> header, and, like most of the standard library, is declared in the <strong>std</strong> namespace<sup>.</sup></p></section><section><title><p>The typeid operator</p></title><section><p>The other way to get runtime information for an object is through the <strong>typeid</strong> operator. This operator returns an object of class <strong>type_info</strong>, which yields information about the type of object to which it was applied. If the type is polymorphic, it gives information about the most derived type that applies (the <emphasis>dynamic type</emphasis>); otherwise it yields static type information. One use of the <strong>typeid</strong> operator is to get the name of the dynamic type of an object as a <strong>const char*</strong>, as you can see in the following example<sup>.</sup></p><p>//: C08:TypeInfo.cpp</p><p>// Illustrates the typeid operator</p><p>#include &lt;iostream&gt;</p><p>#include &lt;typeinfo&gt;</p><p>using namespace std;</p><empty-line/><p>struct PolyBase {virtual ~PolyBase(){}};</p><p>struct PolyDer : PolyBase {};</p><p>struct NonPolyBase {};</p><p>struct NonPolyDer : NonPolyBase {NonPolyDer(int){}};</p><p>int main() {</p><p>  // Test polymorphic Types</p><p>  const PolyDer pd;</p><p>  const PolyBase* ppb = &amp;pd;</p><p>  cout &lt;&lt; typeid(ppb).name() &lt;&lt; endl;</p><p>  cout &lt;&lt; typeid(*ppb).name() &lt;&lt; endl;</p><p>  cout &lt;&lt; boolalpha &lt;&lt; (typeid(*ppb) == typeid(pd))</p><p>    &lt;&lt; endl;</p><p>  cout &lt;&lt; (typeid(PolyDer) == typeid(const PolyDer))</p><p>    &lt;&lt; endl;</p><p>  // Test non-polymorphic Types</p><p>  const NonPolyDer npd(1);</p><p>  const NonPolyBase* nppb = &amp;npd;</p><p>  cout &lt;&lt; typeid(nppb).name() &lt;&lt; endl;</p><p>  cout &lt;&lt; typeid(*nppb).name() &lt;&lt; endl;</p><p>  cout &lt;&lt; (typeid(*nppb) == typeid(npd))</p><p>    &lt;&lt; endl;</p><p>  // Test a built-in type</p><p>  int i;</p><p>  cout &lt;&lt; typeid(i).name() &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The output from this program is</p><p>struct PolyBase const *</p><p>struct PolyDer</p><p>true</p><p>true</p><p>struct NonPolyBase const *</p><p>struct NonPolyBase</p><p>false</p><p>int</p><empty-line/><p>The first output line just echoes the static type of <strong>ppb</strong> because it is a pointer. To get RTTI to kick in, you need to look at the object a pointer or reference is connected to, which is illustrated in the second line. Notice that RTTI ignores top-level <strong>const</strong> and <strong>volatile</strong> qualifiers. With non-polymorphic types, you just get the static type (the type of the pointer itself). As you can see, built-in types are also supported<sup>.</sup></p><p>It turns out that you can’t store the result of a <strong>typeid</strong> operation in a <strong>type_info</strong> object, because there are no accessible constructors and assignment is disallowed; you must use it as we have shown. In addition, the actual string returned by <strong>type_info::name( )</strong> is compiler dependent. Some compilers return "class C" instead of just "C", for instance, for a class named <strong>C</strong>. Applying <strong>typeid</strong> to an expression that dereferences a null pointer will cause a <strong>bad_typeid</strong> exception (also defined in <strong>&lt;typeinfo&gt;</strong>) to be thrown<sup>.</sup></p><p>The following example shows that the class name that <strong>type_info::name( )</strong> returns is fully qualified<sup>.</sup></p><p>//: C08:RTTIandNesting.cpp</p><p>#include &lt;iostream&gt;</p><p>#include &lt;typeinfo&gt;</p><p>using namespace std;</p><empty-line/><p>class One {</p><p>  class Nested {};</p><p>  Nested* n;</p><p>public:</p><p>  One() : n(new Nested) {}</p><p>  ~One() { delete n; }</p><p>  Nested* nested() { return n; }</p><p>};</p><empty-line/><p>int main() {</p><p>  One o;</p><p>  cout &lt;&lt; typeid(*o.nested()).name() &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>Since <strong>Nested</strong> is a member type of the <strong>One</strong> class, the result is <strong>One::Nested</strong><sup><strong>.</strong></sup></p><p>You can also ask a <strong>type_info</strong> object if it precedes another <strong>type_info</strong> object in the implementation-defined "collation sequence" (the native ordering rules for text), using <strong>before(type_info&amp;)</strong>, which returns <strong>true</strong> or <strong>false</strong>. When you say,<sup>.</sup></p><p>if(typeid(me).before(typeid(you))) // ...</p><empty-line/><p>you’re asking if <strong>me</strong> occurs before <strong>you</strong> in the current collation sequence. This is useful should you use <strong>type_info</strong> objects as keys<sup>.</sup></p></section><section><title><p>Casting to intermediate levels</p></title><p>As you saw in the earlier program that used the hierarchy of <strong>Security</strong> classes, <strong>dynamic_cast</strong> can detect both exact types and, in an inheritance hierarchy with multiple levels, intermediate types. Here is another example.</p><p>//: C08:IntermediateCast.cpp</p><p>#include &lt;cassert&gt;</p><p>#include &lt;typeinfo&gt;</p><p>using namespace std;</p><empty-line/><p>class B1 {</p><p>public:</p><p>  virtual ~B1() {}</p><p>};</p><empty-line/><p>class B2 {</p><p>public:</p><p>  virtual ~B2() {}</p><p>};</p><empty-line/><p>class MI : public B1, public B2 {};</p><p>class Mi2 : public MI {};</p><empty-line/><p>int main() {</p><p>  B2* b2 = new Mi2;</p><p>  Mi2* mi2 = dynamic_cast&lt;Mi2*&gt;(b2);</p><p>  MI* mi = dynamic_cast&lt;MI*&gt;(b2);</p><p>  B1* b1 = dynamic_cast&lt;B1*&gt;(b2);</p><p>  assert(typeid(b2) != typeid(Mi2*));</p><p>  assert(typeid(b2) == typeid(B2*));</p><p>  delete b2;</p><p>} ///:~</p><empty-line/><p>This example has the extra complication of multiple inheritance (more on this later in this chapter). If you create an <strong>Mi2</strong> and upcast it to the root (in this case, one of the two possible roots is chosen), the <strong>dynamic_cast</strong> back to either of the derived levels <strong>MI</strong> or <strong>Mi2</strong> is successful<sup>.</sup></p><p>You can even cast from one root to the other:</p><p>  B1* b1 = dynamic_cast&lt;B1*&gt;(b2);</p><empty-line/><p>This is successful because <strong>B2</strong> is actually pointing to an <strong>Mi2</strong> object, which contains a subobject of type <strong>B1</strong>.</p><p>Casting to intermediate levels brings up an interesting difference between <strong>dynamic_cast</strong> and <strong>typeid</strong>. The <strong>typeid</strong> operator always produces a reference to a static <strong>typeinfo</strong> object that describes the dynamic type of the object. Thus, it doesn’t give you intermediate-level information. In the following expression (which is <strong>true</strong>), <strong>typeid</strong> doesn’t see <strong>b2</strong> as a pointer to the derived type, like <strong>dynamic_cast</strong> does:</p><p>typeid(b2) != typeid(Mi2*)</p><empty-line/><p>The type of <strong>b2</strong> is simply the exact type of the pointer:</p><p>typeid(b2) == typeid(B2*)</p><empty-line/></section><section><title><p>void pointers</p></title><p>RTTI only works for complete types, meaning that all class information must be available when <strong>typeid</strong> is used. In particular, it doesn’t work with <strong>void</strong> pointers:</p><p>//: C08:VoidRTTI.cpp</p><p>// RTTI &amp; void pointers</p><p>//!#include &lt;iostream&gt;</p><p>#include &lt;typeinfo&gt;</p><p>using namespace std;</p><empty-line/><p>class Stimpy {</p><p>public:</p><p>  virtual void happy() {}</p><p>  virtual void joy() {}</p><p>  virtual ~Stimpy() {}</p><p>};</p><empty-line/><p>int main() {</p><p>  void* v = new Stimpy;</p><p>  // Error:</p><p>//!  Stimpy* s = dynamic_cast&lt;Stimpy*&gt;(v);</p><p>  // Error:</p><p>//!  cout &lt;&lt; typeid(*v).name() &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>A <strong>void*</strong> truly means "no type information at all."<a l:href="#n106" type="note">[106]</a></p></section><section><title><p>Using RTTI with templates</p></title><p>Class templates work well with RTTI, since all they do is generate classes. As usual, RTTI provides a convenient way to obtain the name of the class you’re in. The following example prints the order of constructor and destructor calls<sup>:</sup></p><p>//: C08:ConstructorOrder.cpp</p><p>// Order of constructor calls</p><p>#include &lt;iostream&gt;</p><p>#include &lt;typeinfo&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;int id&gt; class Announce {</p><p>public:</p><p>  Announce() {</p><p>    cout &lt;&lt; typeid(*this).name()</p><p>         &lt;&lt; " constructor" &lt;&lt; endl;</p><p>  }</p><p>  ~Announce() {</p><p>    cout &lt;&lt; typeid(*this).name()</p><p>         &lt;&lt; " destructor" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class X : public Announce&lt;0&gt; {</p><p>  Announce&lt;1&gt; m1;</p><p>  Announce&lt;2&gt; m2;</p><p>public:</p><p>  X() { cout &lt;&lt; "X::X()" &lt;&lt; endl; }</p><p>  ~X() { cout &lt;&lt; "X::~X()" &lt;&lt; endl; }</p><p>};</p><empty-line/><p>int main() { X x; } ///:~</p><empty-line/><p>This template uses a constant <strong>int</strong> to differentiate one class from another, but type arguments would work as well. Inside both the constructor and destructor, RTTI information produces the name of the class to print. The class <strong>X</strong> uses both inheritance and composition to create a class that has an interesting order of constructor and destructor calls. The output is<sup>:</sup></p><p>Announce&lt;0&gt; constructor</p><p>Announce&lt;1&gt; constructor</p><p>Announce&lt;2&gt; constructor</p><p>X::X()</p><p>X::~X()</p><p>Announce&lt;2&gt; destructor</p><p>Announce&lt;1&gt; destructor</p><p>Announce&lt;0&gt; destructor</p><empty-line/></section></section><section><title><p>Multiple inheritance</p></title><p>Of course, the RTTI mechanisms must work properly with all the complexities of multiple inheritance, including <strong>virtual</strong> base classes (discussed in depth in the next chapter—you may want to come back to this after reading Chapter 9):</p><p>//: C08:RTTIandMultipleInheritance.cpp</p><p>#include &lt;iostream&gt;</p><p>#include &lt;typeinfo&gt;</p><p>using namespace std;</p><empty-line/><p>class BB {</p><p>public:</p><p>  virtual void f() {}</p><p>  virtual ~BB() {}</p><p>};</p><p>class B1 : virtual public BB {};</p><p>class B2 : virtual public BB {};</p><p>class MI : public B1, public B2 {};</p><empty-line/><p>int main() {</p><p>  BB* bbp = new MI; // Upcast</p><p>  // Proper name detection:</p><p>  cout &lt;&lt; typeid(*bbp).name() &lt;&lt; endl;</p><p>  // Dynamic_cast works properly:</p><p>  MI* mip = dynamic_cast&lt;MI*&gt;(bbp);</p><p>  // Can't force old-style cast:</p><p>//! MI* mip2 = (MI*)bbp; // Compile error</p><p>} ///:~</p><empty-line/><p>The <strong>typeid( ) </strong>operation properly detects the name of the actual object, even through the <strong>virtual</strong> base class pointer. The <strong>dynamic_cast</strong> also works correctly. But the compiler won’t even allow you to try to force a cast the old way<sup>:</sup></p><p>MI* mip = (MI*)bbp; // Compile-time error</p><empty-line/><p>The compiler knows this is never the right thing to do, so it requires that you use a <strong>dynamic_cast</strong><sup><strong>.</strong></sup></p></section><section><title><p>Sensible uses for RTTI</p></title><section><p>Because it allows you to discover type information from an anonymous polymorphic pointer, RTTI is ripe for misuse by the novice because RTTI may make sense before virtual functions do. For many people coming from a procedural background, it’s difficult not to organize programs into sets of <strong>switch</strong> statements. They could accomplish this with RTTI and thus lose the important value of polymorphism in code development and maintenance. The intent of C++ is that you use virtual functions throughout your code and that you only use RTTI when you must<sup>.</sup></p><p>However, using virtual functions as they are intended requires that you have control of the base-class definition because at some point in the extension of your program you may discover the base class doesn’t include the virtual function you need. If the base class comes from a library or is otherwise controlled by someone else, a solution to the problem is RTTI: you can derive a new type and add your extra member function. Elsewhere in the code you can detect your particular type and call that member function. This doesn’t destroy the polymorphism and extensibility of the program, because adding a new type will not require you to hunt for switch statements. However, when you add new code in the main body that requires your new feature, you’ll have to detect your particular type<sup>.</sup></p><p>Putting a feature in a base class might mean that, for the benefit of one particular class, all the other classes derived from that base require some meaningless stub for a pure virtual function. This makes the interface less clear and annoys those who must redefine pure virtual functions when they derive from that base class<sup>.</sup></p><p>Finally, RTTI will sometimes solve efficiency problems. If your code uses polymorphism in a nice way, but it turns out that one of your objects reacts to this general-purpose code in a horribly inefficient way, you can pick that type out using RTTI and write case-specific code to improve the efficiency<sup>.</sup></p></section><section><title><p>A trash recycler</p></title><p>To further illustrate a practical use of RTTI, the following program simulates a trash recycler. Different kinds of "trash" are inserted into a single container and then later sorted according to their dynamic types<sup>.</sup></p><p>//: C08:Recycle.cpp</p><p>// A Trash Recycler</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;typeinfo&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../purge.h"</p><p>using namespace std;</p><empty-line/><p>class Trash {</p><p>  float _weight;</p><p>public:</p><p>  Trash(float wt) : _weight(wt) {}</p><p>  virtual float value() const = 0;</p><p>  float weight() const { return _weight; }</p><p>  virtual ~Trash() { cout &lt;&lt; "~Trash()\n"; }</p><p>};</p><p>class Aluminum : public Trash {</p><p>  static float val;</p><p>public:</p><p>  Aluminum(float wt) : Trash(wt) {}</p><p>  float value() const { return val; }</p><p>  static void value(float newval) {</p><p>    val = newval;</p><p>  }</p><p>};</p><p>float Aluminum::val = 1.67;</p><p>class Paper : public Trash {</p><p>  static float val;</p><p>public:</p><p>  Paper(float wt) : Trash(wt) {}</p><p>  float value() const { return val; }</p><p>  static void value(float newval) {</p><p>    val = newval;</p><p>  }</p><p>};</p><p>float Paper::val = 0.10;</p><p>class Glass : public Trash {</p><p>  static float val;</p><p>public:</p><p>  Glass(float wt) : Trash(wt) {}</p><p>  float value() const { return val; }</p><p>  static void value(float newval) {</p><p>    val = newval;</p><p>  }</p><p>};</p><p>float Glass::val = 0.23;</p><empty-line/><p>// Sums up the value of the Trash in a bin:</p><p>template&lt;class Container&gt;</p><p>void sumValue(Container&amp; bin, ostream&amp; os) {</p><p>  typename Container::iterator tally =</p><p>    bin.begin();</p><p>  float val = 0;</p><p>  while(tally != bin.end()) {</p><p>    val += (*tally)-&gt;weight() * (*tally)-&gt;value();</p><p>    os &lt;&lt; "weight of "</p><p>        &lt;&lt; typeid(**tally).name()</p><p>        &lt;&lt; " = " &lt;&lt; (*tally)-&gt;weight() &lt;&lt; endl;</p><p>    tally++;</p><p>  }</p><p>  os &lt;&lt; "Total value = " &lt;&lt; val &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main() {</p><p>  srand(time(0)); // Seed random number generator</p><p>  vector&lt;Trash*&gt; bin;</p><p>  // Fill up the Trash bin:</p><p>  for(int i = 0; i &lt; 30; i++)</p><p>    switch(rand() % 3) {</p><p>      case 0 :</p><p>        bin.push_back(new Aluminum((rand() % 1000)/10.0));</p><p>        break;</p><p>      case 1 :</p><p>        bin.push_back(new Paper((rand() % 1000)/10.0));</p><p>        break;</p><p>      case 2 :</p><p>        bin.push_back(new Glass((rand() % 1000)/10.0));</p><p>        break;</p><p>    }</p><p>  // Note: bins hold exact type of object, not base type:</p><p>  vector&lt;Glass*&gt; glassBin;</p><p>  vector&lt;Paper*&gt; paperBin;</p><p>  vector&lt;Aluminum*&gt; alumBin;</p><p>  vector&lt;Trash*&gt;::iterator sorter = bin.begin();</p><p>  // Sort the Trash:</p><p>  while(sorter != bin.end()) {</p><p>    Aluminum* ap =</p><p>      dynamic_cast&lt;Aluminum*&gt;(*sorter);</p><p>    Paper* pp =</p><p>      dynamic_cast&lt;Paper*&gt;(*sorter);</p><p>    Glass* gp =</p><p>      dynamic_cast&lt;Glass*&gt;(*sorter);</p><p>    if(ap) alumBin.push_back(ap);</p><p>    else if(pp) paperBin.push_back(pp);</p><p>    else if(gp) glassBin.push_back(gp);</p><p>    sorter++;</p><p>  }</p><p>  sumValue(alumBin, cout);</p><p>  sumValue(paperBin, cout);</p><p>  sumValue(glassBin, cout);</p><p>  sumValue(bin, cout);</p><p>  purge(bin);</p><p>} ///:~</p><empty-line/><p>The nature of this problem is that the trash is thrown unclassified into a single bin, so the specific type information is "lost." But later the specific type information must be recovered to properly sort the trash, and so RTTI is used<sup>.</sup></p><p>We can do even better by using a <strong>map</strong> that associates pointers to <strong>type_info</strong> objects with a vector of <strong>Trash</strong> pointers. Since a map requires an ordering predicate, we provide one named <strong>TInfoLess</strong> that calls <strong>type_info::before( )</strong>. As we insert <strong>Trash</strong> pointers into the map, they are associated automatically with their <strong>type_info</strong> key<sup>.</sup></p><p>//: C08:Recycle2.cpp</p><p>// A Trash Recycler</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;map&gt;</p><p>#include &lt;typeinfo&gt;</p><p>#include &lt;utility&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../purge.h"</p><p>using namespace std;</p><empty-line/><p>class Trash {</p><p>  float wt;</p><p>public:</p><p>  Trash(float wt) : wt(wt) {}</p><p>  virtual float value() const = 0;</p><p>  float weight() const { return wt; }</p><p>  virtual ~Trash() { cout &lt;&lt; "~Trash()\n"; }</p><p>};</p><p>class Aluminum : public Trash {</p><p>  static float val;</p><p>public:</p><p>  Aluminum(float wt) : Trash(wt) {}</p><p>  float value() const { return val; }</p><p>  static void value(float newval) {</p><p>    val = newval;</p><p>  }</p><p>};</p><p>float Aluminum::val = 1.67;</p><p>class Paper : public Trash {</p><p>  static float val;</p><p>public:</p><p>  Paper(float wt) : Trash(wt) {}</p><p>  float value() const { return val; }</p><p>  static void value(float newval) {</p><p>    val = newval;</p><p>  }</p><p>};</p><p>float Paper::val = 0.10;</p><p>class Glass : public Trash {</p><p>  static float val;</p><p>public:</p><p>  Glass(float wt) : Trash(wt) {}</p><p>  float value() const { return val; }</p><p>  static void value(float newval) {</p><p>    val = newval;</p><p>  }</p><p>};</p><p>float Glass::val = 0.23;</p><empty-line/><p>// Comparator for type_info pointers</p><p>struct TInfoLess {</p><p>  bool operator()(const type_info* t1, const type_info* t2)</p><p>  const {</p><p>    return t1-&gt;before(*t2);</p><p>  }</p><p>};</p><p>typedef map&lt;const type_info*, vector&lt;Trash*&gt;, TInfoLess&gt;</p><p>  TrashMap;</p><empty-line/><p>// Sums up the value of the Trash in a bin:</p><p>void sumValue(const TrashMap::value_type&amp; p, ostream&amp; os) {</p><p>  vector&lt;Trash*&gt;::const_iterator tally = p.second.begin();</p><p>  float val = 0;</p><p>  while(tally != p.second.end()) {</p><p>    val += (*tally)-&gt;weight() * (*tally)-&gt;value();</p><p>    os &lt;&lt; "weight of "</p><p>       &lt;&lt; p.first-&gt;name()  // type_info::name()</p><p>       &lt;&lt; " = " &lt;&lt; (*tally)-&gt;weight() &lt;&lt; endl;</p><p>    tally++;</p><p>  }</p><p>  os &lt;&lt; "Total value = " &lt;&lt; val &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main() {</p><p>  srand(time(0)); // Seed random number generator</p><p>  TrashMap bin;</p><p>  // Fill up the Trash bin:</p><p>  for(int i = 0; i &lt; 30; i++) {</p><p>    Trash* tp;</p><p>    switch(rand() % 3) {</p><p>      case 0 :</p><p>        tp = new Aluminum((rand() % 1000)/10.0);</p><p>        break;</p><p>      case 1 :</p><p>        tp = new Paper((rand() % 1000)/10.0);</p><p>        break;</p><p>      case 2 :</p><p>        tp = new Glass((rand() % 1000)/10.0);</p><p>        break;</p><p>    }</p><p>    bin[&amp;typeid(*tp)].push_back(tp);</p><p>  }</p><p>  // Print sorted results</p><p>  for(TrashMap::iterator p = bin.begin();</p><p>      p != bin.end(); ++p) {</p><p>    sumValue(*p, cout);</p><p>    purge(p-&gt;second);</p><p>  }</p><p>} ///:~</p><empty-line/><p>We’ve modified <strong>sumValue( )</strong> to call <strong>type_info::name( )</strong> directly, since the <strong>type_info</strong> object is now available there as the first member of the <strong>TrashMap::value_type</strong> pair. This avoids the extra call to <strong>typeid</strong> to get the name of the type of <strong>Trash</strong> being processed that was necessary in the previous version of this program<sup>.</sup></p></section></section><section><title><p>Mechanism and overhead of RTTI</p></title><p>Typically, RTTI is implemented by placing an additional pointer in a class’s virtual function table. This pointer points to the <strong>type_info</strong> structure for that particular type. The effect of a <strong>typeid( )</strong> expression is quite simple: the virtual function table pointer fetches the <strong>type_info</strong> pointer, and a reference to the resulting <strong>type_info</strong> structure is produced. Since this is just a two-pointer dereference operation, it is a constant time operation.</p><p>For a <strong>dynamic_cast&lt;destination*&gt;(source_pointer)</strong>, most cases are quite straightforward: <strong>source_pointer</strong>’s RTTI information is retrieved, and RTTI information for the type <strong>destination*</strong> is fetched. A library routine then determines whether <strong>source_pointer</strong>’s type is of type <strong>destination*</strong> or a base class of <strong>destination*</strong>. The pointer it returns may be adjusted because of multiple inheritance if the base type isn’t the first base of the derived class. The situation is (of course) more complicated with multiple inheritance in which a base type may appear more than once in an inheritance hierarchy and virtual base classes are used.</p><p>Because the library routine used for <strong>dynamic_cast</strong> must check through a list of base classes, the overhead for <strong>dynamic_cast</strong> may be higher than <strong>typeid( )</strong> (but of course you get different information, which may be essential to your solution), and it may take more time to discover a base class than a derived class. In addition, <strong>dynamic_cast</strong> allows you to compare any type to any other type; you aren’t restricted to comparing types within the same hierarchy. This adds extra overhead to the library routine used by <strong>dynamic_cast</strong>.</p></section><section><title><p>Summary</p></title><p>Although normally you upcast a pointer to a base class and then use the generic interface of that base class (via virtual functions), occasionally you get into a corner where things can be more effective if you know the dynamic type of the object pointed to by a base pointer, and that’s what RTTI provides. The most common misuse may come from the programmer who doesn’t understand virtual functions and uses RTTI to do type-check coding instead. The philosophy of C++ seems to be to provide you with powerful tools and guard for type violations and integrity, but if you want to deliberately misuse or get around a language feature, there’s nothing to stop you. Sometimes a slight burn is the fastest way to gain experience.</p></section><section><title><p>Exercises</p></title><p>             1.             Modify <strong>C16:AutoCounter.h</strong> in Volume 1 of this series so that it becomes a useful debugging tool. It will be used as a nested member of each class that you are interested in tracing. Turn <strong>AutoCounter</strong> into a template that takes the class name of the surrounding class as the template argument, and in all the error messages use RTTI to print out the name of the class.</p><p>        58.             Use RTTI to assist in program debugging by printing out the exact name of a template using <strong>typeid( )</strong>. Instantiate the template for various types and see what the results are.</p><p>        59.             Modify the <strong>Instrument</strong> hierarchy from Chapter 14 of Volume 1 by first copying <strong>Wind5.cpp</strong> to a new location. Now add a virtual <strong>ClearSpitValve( )</strong> function to the <strong>Wind</strong> class, and redefine it for all the classes inherited from <strong>Wind</strong>. Instantiate a <strong>TStash</strong> to hold <strong>Instrument</strong> pointers, and fill it with various types of <strong>Instrument</strong> objects created using the <strong>new</strong> operator. Now use RTTI to move through the container looking for objects in class <strong>Wind</strong>, or derived from <strong>Wind</strong>. Call the <strong>ClearSpitValve( )</strong> function for these objects. Notice that it would unpleasantly confuse the Instrument base class if it contained a <strong>ClearSpitValve( )</strong> function<sup>.</sup></p></section></section><section><title><p>9: Multiple inheritance</p></title><section><p>The basic concept of multiple inheritance (MI) sounds simple enough: you create a new type by inheriting from more than one base class. The syntax is exactly what you’d expect, and as long as the inheritance diagrams are simple, MI can be simple as well.</p><p>Or maybe not! MI can introduce a number of ambiguities and strange situations, which are covered in this chapter. But first, it will be helpful to get a little perspective on the subject<sup>.</sup></p></section><section><title><p>Perspective</p></title><p>Before C++, the most successful object-oriented language was Smalltalk. Smalltalk was created from the ground up as an object-oriented language. It is often referred to as <emphasis>pure,</emphasis> whereas C++ is called a <emphasis>hybrid</emphasis> language because it supports multiple programming paradigms, not just the object-oriented paradigm. One of the design decisions made with Smalltalk was that all classes would be derived in a single hierarchy, rooted in a single base class (called <strong>Object</strong>—this is the model for the <emphasis>object-based hierarchy</emphasis>). You cannot create a new class in Smalltalk without deriving it from an existing class, which is why it takes a certain amount of time to become productive in Smalltalk: you must learn the class library before you can start making new classes. The Smalltalk class hierarchy is therefore a single monolithic tree.</p><p>Classes in Smalltalk usually have a number of things in common, and they always have <emphasis>some</emphasis> things in common (the characteristics and behaviors of <strong>Object</strong>), so you almost never run into a situation in which you need to inherit from more than one base class. However, with C++ you can create as many hierarchy trees as you want. Therefore, for logical completeness the language must be able to combine more than one class at a time—thus the need for multiple inheritance.</p><p>It was not a crystal clear, however, that programmers could not get by without multiple inheritance, and there was (and still is) a lot of disagreement about whether it is really essential in C++. MI was added in AT&amp;T <strong>cfront</strong> release 2.0 and was the first significant change to the language. Since then, a number of other features have been added (notably templates and exceptions) that change the way we think about programming and place MI in a much less important role. You can think of MI as a "minor" language feature that is seldom involved in your daily design decisions.</p><p>One of the most pressing issues at the time that drove MI involved containers. Suppose you want to create a container that everyone can easily use. One approach is to use <strong>void*</strong> as the type inside the container. The Smalltalk approach, however, is to make a container that holds <strong>Object</strong>s. (Remember that <strong>Object</strong> is the base type of the entire Smalltalk hierarchy.) Because everything in Smalltalk is ultimately derived from <strong>Object</strong>, any container that holds <strong>Object</strong>s can hold anything<sup>.</sup></p><p>Now consider the situation in C++. Suppose vendor <strong>A</strong> creates an object-based hierarchy that includes a useful set of containers including one you want to use called <strong>Holder</strong>. Now you come across vendor <strong>B</strong>’s class hierarchy that contains some other class that is important to you, a <strong>BitImage</strong> class, for example, that holds graphic images. The only way to make a <strong>Holder</strong> of <strong>BitImage</strong>s is to derive a new class from both <strong>Object</strong>, so it can be held in the <strong>Holder</strong>, and <strong>BitImage</strong>:</p><p><image l:href="#7"/></p><p>This was seen as an important reason for MI, and a number of class libraries were built on this model. However, as you saw in Chapter 5, the addition of templates has changed the way containers are created, so this situation isn’t a driving issue for MI.</p><p>The other reason you may need MI is related to design. You can intentionally use MI to make a design more flexible or useful (or at least seemingly so). An example of this is in the original <strong>iostream</strong> library design (which still persists in today’s template design, as you saw in Chapter 4):</p><p><image l:href="#8"/></p><p>Both <strong>istream</strong> and <strong>ostream</strong> are useful classes by themselves, but they can also be derived from simultaneously by a class that combines both their characteristics and behaviors. The class <strong>ios</strong> provides what is common to all stream classes, and so in this case MI is a code-factoring mechanism<sup>.</sup></p><p>Regardless of what motivates you to use MI, it’s harder to use than it might appear<sup>.</sup></p></section><section><title><p>Interface inheritance</p></title><p>One use of multiple inheritance that is not controversial pertains to <emphasis>interface inheritance</emphasis>. In C++, all inheritance is <emphasis>implementation inheritance</emphasis>, because everything in a base class, interface and implementation, becomes part of a derived class. It is not possible to inherit only part of a class (the interface alone, say). As Chapter 14 of Volume 1 explains, private and protected inheritance make it possible to restrict access to members inherited from base classes when used by clients of a derived class object, but this doesn’t affect the derived class; it still contains all base class data and can access all non-private base class members<sup>.</sup></p><p>Interface inheritance, on the other hand, only adds member function declarations to a derived class interface and is not directly supported in C++. The usual technique to simulate interface inheritance in C++ is to derive from an <emphasis>interface class</emphasis>, which is a class that contains only declarations (no data or function bodies). These declarations will be pure virtual functions, of course. Here is an example<sup>.</sup></p><p>//: C09:Interfaces.cpp</p><p>// Multiple interface inheritance</p><p>#include &lt;iostream&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>class Printable {</p><p>public:</p><p>  virtual ~Printable() {}</p><p>  virtual void print(ostream&amp;) const = 0;</p><p>};</p><empty-line/><p>class Intable {</p><p>public:</p><p>  virtual ~Intable() {}</p><p>  virtual int toInt() const = 0;</p><p>};</p><empty-line/><p>class Stringable {</p><p>public:</p><p>  virtual ~Stringable() {}</p><p>  virtual string toString() const = 0;</p><p>};</p><empty-line/><p>class Able : public Printable,</p><p>             public Intable,</p><p>             public Stringable {</p><p>  int myData;</p><p>public:</p><p>  Able(int x) {</p><p>    myData = x;</p><p>  }</p><p>  void print(ostream&amp; os) const {</p><p>    os &lt;&lt; myData;</p><p>  }</p><p>  int toInt() const {</p><p>    return myData;</p><p>  }</p><p>  string toString() const {</p><p>    ostringstream os;</p><p>    os &lt;&lt; myData;</p><p>    return os.str();</p><p>  }</p><p>};</p><empty-line/><p>void testPrintable(const Printable&amp; p) {</p><p>  p.print(cout);</p><p>  cout &lt;&lt; endl;</p><p>}</p><p>void testIntable(const Intable&amp; n) {</p><p>  int i = n.toInt() + 1;</p><p>  cout &lt;&lt; i &lt;&lt; endl;</p><p>}</p><p>void testStringable(const Stringable&amp; s) {</p><p>  string buf = s.toString() + "th";</p><p>  cout &lt;&lt; buf &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main() {</p><p>  Able a(7);</p><p>  testPrintable(a);</p><p>  testIntable(a);</p><p>  testStringable(a);</p><p>} ///:~</p><empty-line/><p>Only pure virtual functions are inherited from classes <strong>Printable</strong>, <strong>Intable</strong>, and <strong>Stringable</strong>, which must therefore be implemented in derived class overrides, which the <strong>Able</strong> class provides. This gives <strong>Able</strong> objects multiple "is-a" relationships. The object <strong>a</strong> can act as a <strong>Printable</strong> object because its class <strong>Able</strong> derives publicly from <strong>Printable</strong> and provides an implementation for <strong>print( )</strong>. The test functions have no need to know the most-derived type of their parameter; they just need an object that is substitutable for their parameter’s type<sup>.</sup></p><p>As usual, a template solution is more compact:</p><p>//: C09:Interfaces2.cpp</p><p>// Implicit interface inheritance via templates</p><p>#include &lt;iostream&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>class Able {</p><p>  int myData;</p><p>public:</p><p>  Able(int x) {</p><p>    myData = x;</p><p>  }</p><p>  void print(ostream&amp; os) const {</p><p>    os &lt;&lt; myData;</p><p>  }</p><p>  int toInt() const {</p><p>    return myData;</p><p>  }</p><p>  string toString() const {</p><p>    ostringstream os;</p><p>    os &lt;&lt; myData;</p><p>    return os.str();</p><p>  }</p><p>};</p><empty-line/><p>template&lt;class Printable&gt;</p><p>void testPrintable(const Printable&amp; p) {</p><p>  p.print(cout);</p><p>  cout &lt;&lt; endl;</p><p>}</p><p>template&lt;class Intable&gt;</p><p>void testIntable(const Intable&amp; n) {</p><p>  int i = n.toInt() + 1;</p><p>  cout &lt;&lt; i &lt;&lt; endl;</p><p>}</p><p>template&lt;class Stringable&gt;</p><p>void testStringable(const Stringable&amp; s) {</p><p>  string buf = s.toString() + "th";</p><p>  cout &lt;&lt; buf &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main() {</p><p>  Able a(7);</p><p>  testPrintable(a);</p><p>  testIntable(a);</p><p>  testStringable(a);</p><p>} ///:<sup>~</sup></p><empty-line/><p>The names <strong>Printable</strong>, <strong>Intable,</strong> and <strong>Stringable</strong> are now just template parameters that assume the existence of the operations indicated in their respective contexts. Some people are more comfortable with the first version, because the type names guarantee by inheritance that the expected interfaces are implemented. Others are content with the fact that if the operations required by the test functions are not satisfied by their template type arguments, the error is still caught at compile time. The latter approach is technically a "weaker" form of type checking than the former (inheritance) approach, but the effect on the programmer (and the program) is the same. This is one form of weak typing that is acceptable to many of today’s C++ programmers<sup>.</sup></p></section><section><title><p>Implementation inheritance</p></title><p>As we stated earlier, C++ provides only implementation inheritance, meaning that you inherit everything from all your base classes. This can be a good thing, of course, because it frees you from having to implement <emphasis>everything</emphasis> in the derived class, as we had to do with the interface inheritance examples earlier. A common use of multiple inheritance involves using <emphasis>mixin classes</emphasis>, which are classes not intended to be instantiated independently, but exist to add capabilities to other classes through inheritance<sup>.</sup></p><p>As an example, suppose we are clients of a class that supports access to a database. We will likely only have a header file available (which is part of the point we are about to make), but for illustration, assume the following, simple implementation of a <strong>Database</strong> class<sup>:</sup></p><p>//: C09:Database.h</p><p>// A prototypical resource class</p><p>#ifndef DATABASE_H</p><p>#define DATABASE_H</p><p>#include &lt;iostream&gt;</p><p>#include &lt;stdexcept&gt;</p><p>#include &lt;string&gt;</p><p>using std::cout;</p><p>using std::string;</p><p>using std::runtime_error;</p><empty-line/><p>struct DatabaseError : runtime_error {</p><p>  DatabaseError(const string&amp; msg) : runtime_error(msg)</p><p>  {}</p><p>};</p><empty-line/><p>class Database {</p><p>public:</p><p>  Database(const string&amp; dbStr) : dbid(dbStr) {}</p><p>  virtual ~Database(){}</p><p>  void open() throw(DatabaseError) {</p><p>    cout &lt;&lt; "connected to " &lt;&lt; dbid &lt;&lt; '\n';</p><p>  }</p><p>  void close() {</p><p>    cout &lt;&lt; dbid &lt;&lt; " closed\n";</p><p>  }</p><p>  //Other database functions...</p><p>private:</p><p>  string dbid;</p><p>};</p><p>#endif ///:~</p><empty-line/><p>We’re leaving out actual database functionality (storing, retrieving, and so on), but that’s actually not important here. Using this class requires a database connection string and that you call <strong>Database::open( )</strong> to connect and <strong>Database::close( )</strong> to disconnect<sup>:</sup></p><p>//: C09:UseDatabase.cpp</p><p>#include "Database.h"</p><p>int main() {</p><p>  Database db("MyDatabase");</p><p>  db.open();</p><p>  // Use other db functions...</p><p>  db.close();</p><p>}</p><p>/* Output:</p><p>connected to MyDatabase</p><p>MyDatabase closed</p><p>*/ ///:<sup>~</sup></p><empty-line/><p>In a typical client-server situation, a client will have multiple objects sharing a connection to a database. It is important that the database eventually be closed, but only after access to it is no longer required. It is common to encapsulate this behavior through a class that tracks the number of client entities using the database connection and to automatically terminate the connection when that count goes to zero. To add reference counting to the <strong>Database</strong> class, we create a mixin class named <strong>Countable</strong> and mix it into the <strong>Database</strong> class by creating a new class, <strong>DBConnection</strong>, through multiple inheritance. Here’s the <strong>Countable</strong> mixin class<sup>:</sup></p><p>//: C09:Countable.h</p><p>// A "mixin" class</p><p>#ifndef COUNTABLE_H</p><p>#define COUNTABLE_H</p><p>#include &lt;cassert&gt;</p><empty-line/><p>class Countable {</p><p>public:</p><p>  long attach() { return ++count; }</p><p>  long detach() {</p><p>    return (--count &gt; 0) ? count : (delete this, 0);</p><p>  }</p><p>  long refCount() const { return count; }</p><p>protected:</p><p>  Countable() { count = 0; }</p><p>  virtual ~Countable() { assert(count == 0); }</p><p>private:</p><p>  long count;</p><p>};</p><p>#endif ///:<sup>~</sup></p><empty-line/><p>It is evident that this is not a standalone class because its constructor is <strong>protected</strong>; it therefore requires a friend or a derived class to use it. It is important that the destructor is virtual, of course, because it is called only from the <strong>delete this</strong> statement in <strong>detach( )</strong>, and we of course want derived objects to be completely destroyed.<a l:href="#n107" type="note">[107]</a> The <strong>DBConnection</strong> class derives from both <strong>Database</strong> and <strong>Countable</strong> and provides a static <strong>create( )</strong> function that initializes its <strong>Countable</strong> subobject. (This is an example of the Factory Method design pattern, discussed in the next chapter.<sup>)</sup></p><p>//: C09:DBConnection.h</p><p>// Uses a "mixin" class</p><p>#ifndef DBCONNECTION_H</p><p>#define DBCONNECTION_H</p><p>#include "Countable.h"</p><p>#include "Database.h"</p><p>#include &lt;cassert&gt;</p><p>#include &lt;string&gt;</p><p>using std::string;</p><empty-line/><p>class DBConnection : public Database, public Countable {</p><p>public:</p><p>  static DBConnection* create(const string&amp; dbStr)</p><p>  throw(DatabaseError) {</p><p>    DBConnection* con = new DBConnection(dbStr);</p><p>    con-&gt;attach();</p><p>    assert(con-&gt;refCount() == 1);</p><p>    return con;</p><p>  }</p><p>// Other added functionality as desired...</p><p>protected:</p><p>  DBConnection(const string&amp; dbStr) throw(DatabaseError)</p><p>  : Database(dbStr) {</p><p>    open();</p><p>  }</p><p>  ~DBConnection() {</p><p>    close();</p><p>  }</p><p>private:</p><p>  // Disallow copy</p><p>  DBConnection(const DBConnection&amp;);</p><p>  DBConnection&amp; operator=(const DBConnection&amp;);</p><p>};</p><p>#endif ///:<sup>~</sup></p><empty-line/><p>We now have a reference-counted database connection without modifying the <strong>Database</strong> class, and we can safely assume that it will not be surreptitiously terminated. The opening and closing is done using the Resource Acquisition Is Initialization idiom (RAII) mentioned in Chapter 1 via the <strong>DBConnection</strong> constructor and destructor. This makes using a <strong>DBConnection</strong> easy to use, as the following program shows<sup>.</sup></p><p>//: C09:UseDatabase2.cpp</p><p>// Tests the Countable "mixin" class</p><p>#include &lt;cassert&gt;</p><p>#include "DBConnection.h"</p><empty-line/><p>class DBClient {</p><p>public:</p><p>  DBClient(DBConnection* dbCon) {</p><p>    db = dbCon;</p><p>    db-&gt;attach();</p><p>  }</p><p>  ~DBClient() {</p><p>    db-&gt;detach();</p><p>  }</p><p>  // Other database requests using db…</p><p>private:</p><p>  DBConnection* db;</p><p>};</p><empty-line/><p>int main() {</p><p>  DBConnection* db = DBConnection::create("MyDatabase");</p><p>  assert(db-&gt;refCount() == 1);</p><p>  DBClient c1(db);</p><p>  assert(db-&gt;refCount() == 2);</p><p>  DBClient c2(db);</p><p>  assert(db-&gt;refCount() == 3);</p><p>  // Use database, then release attach from original create</p><p>  db-&gt;detach();</p><p>  assert(db-&gt;refCount() == 2);</p><p>} ///:<sup>~</sup></p><empty-line/><p>The call to <strong>DBConnection::create( )</strong> calls <strong>attach( )</strong>, so when we’re finished, we must explicitly call <strong>detach( )</strong> to release the original hold on the connection. Note that the <strong>DBClient</strong> class also uses RAII to manage its use of the connection. When the program terminates, the destructors for the two <strong>DBClient</strong> objects will decrement the reference count (by calling <strong>detach( )</strong>, which <strong>DBConnection</strong> inherited from <strong>Countable</strong>), and the database connection will be closed when the count reaches zero after the object <strong>c1</strong> is destroyed. (This is because of <strong>Countable</strong>’s virtual destructor, as we explained earlier.<sup>)</sup></p><p>A template approach is commonly used for mixin inheritance, allowing the user to specify at compile time which flavor of mixin is desired. This way you can use different reference-counting approaches without explicitly defining <strong>DBConnection</strong> twice. Here’s how it’s done<sup>.</sup></p><p>//: C09:DBConnection2.h</p><p>// A parameterized mixin</p><p>#ifndef DBCONNECTION_H</p><p>#define DBCONNECTION_H</p><p>#include "Database.h"</p><p>#include &lt;cassert&gt;</p><p>#include &lt;string&gt;</p><p>using std::string;</p><empty-line/><p>template&lt;class Counter&gt;</p><p>class DBConnection : public Database, public Counter {</p><p>public:</p><p>  static DBConnection* create(const string&amp; dbStr)</p><p>  throw(DatabaseError) {</p><p>    DBConnection* con = new DBConnection(dbStr);</p><p>    con-&gt;attach();</p><p>    assert(con-&gt;refCount() == 1);</p><p>    return con;</p><p>  }</p><p>// Other added functionality as desired...</p><p>protected:</p><p>  DBConnection(const string&amp; dbStr) throw(DatabaseError)</p><p>  : Database(dbStr) {</p><p>    open();</p><p>  }</p><p>  ~DBConnection() {</p><p>    close();</p><p>  }</p><p>private:</p><p>  // Disallow copy</p><p>  DBConnection(const DBConnection&amp;);</p><p>  DBConnection&amp; operator=(const DBConnection&amp;);</p><p>};</p><p>#endif ///:<sup>~</sup></p><empty-line/><p>The only change here is the template prefix to the class definition (and renaming <strong>Countable</strong> to <strong>Counter</strong> for clarity). We could also make the database class a template parameter (had we multiple database access classes to choose from), but it is not a mixin, per se, since it is a standalone class. The following example uses the original <strong>Countable</strong> as the <strong>Counter</strong> mixin type, but we could use any type that implements the appropriate interface (<strong>attach( )</strong>, <strong>detach( )</strong>, and so on)<sup>.</sup></p><p>//: C09:UseDatabase3.cpp</p><p>// Tests a parameterized "mixin" class</p><p>#include &lt;cassert&gt;</p><p>#include "Countable.h"</p><p>#include "DBConnection2.h"</p><empty-line/><p>class DBClient {</p><p>public:</p><p>  DBClient(DBConnection&lt;Countable&gt;* dbCon) {</p><p>    db = dbCon;</p><p>    db-&gt;attach();</p><p>  }</p><p>  ~DBClient() {</p><p>    db-&gt;detach();</p><p>  }</p><p>private:</p><p>  DBConnection&lt;Countable&gt;* db;</p><p>};</p><empty-line/><p>int main() {</p><p>  DBConnection&lt;Countable&gt;* db =</p><p>    DBConnection&lt;Countable&gt;::create("MyDatabase");</p><p>  assert(db-&gt;refCount() == 1);</p><p>  DBClient c1(db);</p><p>  assert(db-&gt;refCount() == 2);</p><p>  DBClient c2(db);</p><p>  assert(db-&gt;refCount() == 3);</p><p>  db-&gt;detach();</p><p>  assert(db-&gt;refCount() == 2);</p><p>} ///:<sup>~</sup></p><empty-line/><p>The general pattern for multiple parameterized mixins is simply:</p><p>template&lt;class Mixin1, class Mixin2, … , class MixinK&gt;</p><p>class Subject : public Mixin1,</p><p> public Mixin2,</p><p> …</p><p>                public MixinK {..};</p><empty-line/></section><section><title><p>Duplicate subobjects</p></title><p>When you inherit from a base class, you get a copy of all the data members of that base class in your derived class. The following program shows how multiple base subobjects might be laid out in memory.<a l:href="#n108" type="note">[108]</a></p><p>//: C09:Offset.cpp</p><p>// Illustrates layout of subobjects with MI</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class A {</p><p>  int x;</p><p>};</p><empty-line/><p>class B {</p><p>  int y;</p><p>};</p><empty-line/><p>class C : public A, public B {</p><p>  int z;</p><p>};</p><empty-line/><p>int main() {</p><p>  cout &lt;&lt; "sizeof(A) == " &lt;&lt; sizeof(A) &lt;&lt; endl;</p><p>  cout &lt;&lt; "sizeof(B) == " &lt;&lt; sizeof(B) &lt;&lt; endl;</p><p>  cout &lt;&lt; "sizeof(C) == " &lt;&lt; sizeof(C) &lt;&lt; endl;</p><p>  C c;</p><p>  cout &lt;&lt; "&amp;c == " &lt;&lt; &amp;c &lt;&lt; endl;</p><p>  A* ap = &amp;c;</p><p>  B* bp = &amp;c;</p><p>  cout &lt;&lt; "ap == " &lt;&lt; static_cast&lt;void*&gt;(ap) &lt;&lt; endl;</p><p>  cout &lt;&lt; "bp == " &lt;&lt; static_cast&lt;void*&gt;(bp) &lt;&lt; endl;</p><p>  C* cp = static_cast&lt;C*&gt;(bp);</p><p>  cout &lt;&lt; "cp == " &lt;&lt; static_cast&lt;void*&gt;(cp) &lt;&lt; endl;</p><p>  cout &lt;&lt; "bp == cp? " &lt;&lt; boolalpha &lt;&lt; (bp == cp) &lt;&lt; endl;</p><p>  cp = 0;</p><p>  bp = cp;</p><p>  cout &lt;&lt; bp &lt;&lt; endl;</p><p>}</p><p>/* Output:</p><p>sizeof(A) == 4</p><p>sizeof(B) == 4</p><p>sizeof(C) == 12</p><p>&amp;c == 1245052</p><p>ap == 1245052</p><p>bp == 1245056</p><p>cp == 1245052</p><p>bp == cp? true</p><p>0</p><p>*/ ///:<sup>~</sup></p><empty-line/><p>As you can see, the <strong>B</strong> portion of the object <strong>c</strong> is offset 4 bytes from the beginning of the entire object, suggesting the following layout:</p><p><image l:href="#9"/></p><p>The object <strong>c</strong> begins with it’s <strong>A</strong> subobject, then the <strong>B</strong> portion, and finally the data from the complete type <strong>C</strong> itself. Since a <strong>C</strong> is-an <strong>A</strong> and is-a <strong>B</strong>, it is possible to upcast to either base type. When upcasting to an A, the resulting pointer points to the A portion, which happens to be at the beginning of the C object, so the address <strong>ap</strong> is the same as the expression <strong>&amp;c</strong>. When upcasting to a <strong>B</strong>, however, the resulting pointer must point to where the <strong>B</strong> subobject actually resides, because class B knows nothing about class <strong>C</strong> (or class <strong>A</strong>, for that matter). In other words, the object pointed to by <strong>bp</strong> must be able to behave as a standalone <strong>B</strong> object (except for any required polymorphic behavior, of course)<sup>.</sup></p><p>When casting <strong>bp</strong> back to a <strong>C*</strong>, since the original object was a <strong>C</strong> in the first place, the location where the <strong>B</strong> subobject resides is known, so the pointer is adjusted back to the original address of the complete object. If <strong>bp</strong> had been pointing to a standalone <strong>B</strong> object instead of a <strong>C</strong> object in the first place, the cast would be illegal.<a l:href="#n109" type="note">[109]</a> Furthermore, in the comparison <strong>bp == cp</strong>, <strong>cp</strong> is implicitly converted to a <strong>B*</strong>, since that is the only way to make the comparison meaningful in general (that is, upcasting is always allowed), hence the <strong>true</strong> result. So when converting back and forth between subobjects and complete types, the appropriate offset is applied<sup>.</sup></p><p>The null pointer requires special handling, obviously, since blindly subtracting an offset when converting to or from a <strong>B</strong> subobject will result in an invalid address if the pointer was zero to start with. For this reason, when casting to or from a <strong>B*</strong>, the compiler generates logic to check first to see if the pointer is zero. If it isn’t, it applies the offset; otherwise, it leaves it as zero<sup>.</sup></p><p>With the syntax we’ve seen so far, if you have multiple base classes, and if those base classes in turn have a common base class, you will have two copies of the top-level base, as you can see in the following example<sup>.</sup></p><p>//: C09:Duplicate.cpp</p><p>// Shows duplicate subobjects</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Top {</p><p>  int x;</p><p>public:</p><p>  Top(int n) { x = n; }</p><p>};</p><empty-line/><p>class Left : public Top {</p><p>  int y;</p><p>public:</p><p>  Left(int m, int n) : Top(m) { y = n; }</p><p>};</p><empty-line/><p>class Right : public Top {</p><p>  int z;</p><p>public:</p><p>  Right(int m, int n) : Top(m) { z = n; }</p><p>};</p><empty-line/><p>class Bottom : public Left, public Right {</p><p>  int w;</p><p>public:</p><p>  Bottom(int i, int j, int k, int m)</p><p>  : Left(i, k), Right(j, k) { w = m; }</p><p>};</p><empty-line/><p>int main() {</p><p>  Bottom b(1, 2, 3, 4);</p><p>  cout &lt;&lt; sizeof b &lt;&lt; endl; // 20</p><p>} ///:<sup>~</sup></p><empty-line/><p>Since the size of <strong>b</strong> is 20 bytes,<a l:href="#n110" type="note">[110]</a> there are five integers altogether in a complete <strong>Bottom</strong> object. A typical class diagram for this scenario usually appears as:</p><p><image l:href="#10"/></p><p>This is the so-called "diamond inheritance", but in this case it would be better rendered as<sup>:</sup></p><p><image l:href="#11"/></p><p>The awkwardness of this design surfaces in the constructor for the <strong>Bottom</strong> class in the previous code. The user thinks that only four integers are required, but which arguments should be passed to the two parameters that <strong>Left</strong> and <strong>Right</strong> require? Although this design is not inherently "wrong," it is usually not what an application calls for. It also presents a problem when trying to convert a pointer to a <strong>Bottom</strong> object to a pointer to <strong>Top</strong>. As we showed earlier, the address may need to be adjusted, depending on where the subobject resides within the complete object, but in this case there are <emphasis>two</emphasis><strong>Top</strong> subobjects to choose from. The compiler doesn’t know which to choose, so such an upcast is ambiguous and therefore not allowed. The same reasoning explains why a <strong>Bottom</strong> object would not be able to call a function that is only defined in <strong>Top</strong>. If such a function <strong>Top::f( )</strong> existed, calling <strong>b.f( )</strong> above would need to refer to a <strong>Top</strong> subobject as a context in which to execute, and there are two to choose between<sup>.</sup></p></section><section><title><p>Virtual base classes</p></title><p>What we usually want in such cases is <emphasis>true</emphasis> diamond inheritance, in which a single <strong>Top</strong> object is shared by both <strong>Left</strong> and <strong>Right</strong> subobjects within a complete <strong>Bottom</strong> object, which is what the first class diagram depicts. This is achieved by making <strong>Top</strong> a <emphasis>virtual base class</emphasis> of <strong>Left</strong> and <strong>Right</strong><sup><strong>:</strong></sup></p><p>//: C09:VirtualBase.cpp</p><p>// Shows a shared subobject via a virtual base</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Top {</p><p>protected:</p><p>  int x;</p><p>public:</p><p>  Top(int n) { x = n; }</p><p>  virtual ~Top(){}</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Top&amp; t) {</p><p>    return os &lt;&lt; t.x;</p><p>  }</p><p>};</p><empty-line/><p>class Left : virtual public Top {</p><p>protected:</p><p>  int y;</p><p>public:</p><p>  Left(int m, int n) : Top(m) { y = n; }</p><p>};</p><empty-line/><p>class Right : virtual public Top {</p><p>protected:</p><p>  int z;</p><p>public:</p><p>  Right(int m, int n) : Top(m) { z = n; }</p><p>};</p><empty-line/><p>class Bottom : public Left, public Right {</p><p>  int w;</p><p>public:</p><p>  Bottom(int i, int j, int k, int m)</p><p>  : Top(i), Left(0, j), Right(0, k) { w = m; }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Bottom&amp; b) {</p><p>    return os &lt;&lt; b.x &lt;&lt; ',' &lt;&lt; b.y &lt;&lt; ',' &lt;&lt; b.z</p><p>      &lt;&lt; ',' &lt;&lt; b.w;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  Bottom b(1, 2, 3, 4);</p><p>  cout &lt;&lt; sizeof b &lt;&lt; endl;</p><p>  cout &lt;&lt; b &lt;&lt; endl;</p><p>  cout &lt;&lt; static_cast&lt;void*&gt;(&amp;b) &lt;&lt; endl;</p><p>  Top* p = static_cast&lt;Top*&gt;(&amp;b);</p><p>  cout &lt;&lt; *p &lt;&lt; endl;</p><p>  cout &lt;&lt; static_cast&lt;void*&gt;(p) &lt;&lt; endl;</p><p>  cout &lt;&lt; dynamic_cast&lt;void*&gt;(p) &lt;&lt; endl;</p><p>} ///:<sup>~</sup></p><empty-line/><p>Each virtual base of a given type refers to the same object, no matter where it appears in the hierarchy.<a l:href="#n111" type="note">[111]</a> This means that when a <strong>Bottom</strong> object is instantiated, the object layout may look something like this<sup>:</sup></p><p><image l:href="#12"/></p><empty-line/><p>The <strong>Left</strong> and <strong>Right</strong> subobjects each have a pointer (or some conceptual equivalent) to the shared <strong>Top</strong> subobject, and all references to that subobject in <strong>Left</strong> and <strong>Right</strong> member functions will go through those these pointers.<a l:href="#n112" type="note">[112]</a> In this case, there is no ambiguity when upcasting from a <strong>Bottom</strong> to a <strong>Top</strong> object, since there is only one <strong>Top</strong> object to convert to<sup>.</sup></p><p>The output of the previous program is as follows:</p><p>36</p><p>1,2,3,4</p><p>1245032</p><p>1</p><p>1245060</p><p>1245032</p><empty-line/><p>The addresses printed suggest that this particular implementation does indeed store the <strong>Top</strong> subobject at the end of the complete object (although it’s not really important where it goes). The result of a <strong>dynamic_cast</strong> to <strong>void*</strong> always resolves to the address of the complete object<sup>.</sup></p><p>We made the <strong>Top</strong> destructor virtual so we could apply the <strong>dynamic_cast</strong> operator. If you remove that virtual destructor (and the <strong>dynamic_cast</strong> statement so the program will compile), the size of <strong>Bottom</strong> decreases to 24 bytes. That seems to be a decrease equivalent to the size of three pointers. What gives? </p><p>It’s important not to take these numbers too literally. Other compilers we use manage only to increase the size by four bytes when the virtual constructor is added. Not being compiler writers, we can’t tell you their secrets. We can tell you, however, that with multiple inheritance, a derived object must behave as if it has multiple VPTRs, one for each of its direct base classes that also have virtual functions. It’s as simple as that. Compilers can make whatever optimizations its authors can invent, but the behavior must be the same<sup>.</sup></p><p>Certainly the strangest thing in the previous code is the initializer for <strong>Top</strong> in the <strong>Bottom</strong> constructor. Normally one doesn’t worry about initializing subobjects beyond direct base classes, since all classes take care of initializing their own bases. There are, however, multiple paths from <strong>Bottom</strong> to <strong>Top</strong>, so relying on the intermediate classes <strong>Left</strong> and <strong>Right</strong> to pass along the necessary initialization data results in an ambiguity (whose responsibility is it?)! For this reason, it is always the responsibility of the <emphasis>most derived class</emphasis> to initialize a virtual base. But what about the expressions in the <strong>Left</strong> and <strong>Right</strong> constructors that also initialize <strong>Top</strong>? They are certainly necessary when creating standalone <strong>Left</strong> or <strong>Right</strong> objects, but must be <emphasis>ignored</emphasis> when a <strong>Bottom</strong> object is created (hence the zeros in their initializers in the <strong>Bottom</strong> constructor—any values in those slots are ignored when the <strong>Left</strong> and <strong>Right</strong> constructors execute in the context of a <strong>Bottom</strong> object). The compiler takes care of all this for you, but it’s important to understand where the responsibility lies. Always make sure that <emphasis>all concrete (nonabstract) classes</emphasis> in a multiple inheritance hierarchy are aware of any virtual bases and initialize them appropriately<sup>.</sup></p><p>These rules of responsibility apply not only to initialization but to all operations that span the class hierarchy. Consider the stream inserter in the previous code. We made the data protected so we could "cheat" and access inherited data in <strong>operator&lt;&lt;(ostream&amp;, const Bottom&amp;)</strong>. It usually makes more sense to assign the work of printing each subobject to its corresponding class and have the derived class call its base class functions as needed. What would happen if we tried that with <strong>operator&lt;&lt;( )</strong>, as the following code illustrates? </p><p>//: C09:VirtualBase2.cpp</p><p>// Shows how not to implement operator&lt;&lt;</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Top {</p><p>  int x;</p><p>public:</p><p>  Top(int n) { x = n; }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Top&amp; t) {</p><p>    return os &lt;&lt; t.x;</p><p>  }</p><p>};</p><empty-line/><p>class Left : virtual public Top {</p><p>  int y;</p><p>public:</p><p>  Left(int m, int n) : Top(m) { y = n; }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Left&amp; l) {</p><p>    return os &lt;&lt; static_cast&lt;const Top&amp;&gt;(l) &lt;&lt; ',' &lt;&lt; l.y;</p><p>  }</p><p>};</p><empty-line/><p>class Right : virtual public Top {</p><p>  int z;</p><p>public:</p><p>  Right(int m, int n) : Top(m) { z = n; }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Right&amp; r) {</p><p>    return os &lt;&lt; static_cast&lt;const Top&amp;&gt;(r) &lt;&lt; ',' &lt;&lt; r.z;</p><p>  }</p><p>};</p><empty-line/><p>class Bottom : public Left, public Right {</p><p>  int w;</p><p>public:</p><p>  Bottom(int i, int j, int k, int m)</p><p>  : Top(i), Left(0, j), Right(0, k) { w = m; }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Bottom&amp; b) {</p><p>    return os &lt;&lt; static_cast&lt;const Left&amp;&gt;(b)</p><p>      &lt;&lt; ',' &lt;&lt; static_cast&lt;const Right&amp;&gt;(b)</p><p>      &lt;&lt; ',' &lt;&lt; b.w;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  Bottom b(1, 2, 3, 4);</p><p>  cout &lt;&lt; b &lt;&lt; endl;  // 1,2,1,3,4</p><p>} ///:~</p><empty-line/><p>You can’t just blindly share the responsibility upward in the usual fashion because the <strong>Left</strong> and <strong>Right</strong> stream inserters each call the <strong>Top</strong> inserter, and again there will be duplication of data. Instead you need to mimic what the compiler automatically does with initialization. One solution is to provide special functions in the classes that know about the virtual base class, which ignore the virtual base when printing (leaving the job to the most derived class)<sup>:</sup></p><p>//: C09:VirtualBase3.cpp</p><p>// A correct stream inserter</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Top {</p><p>  int x;</p><p>public:</p><p>  Top(int n) { x = n; }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Top&amp; t) {</p><p>    return os &lt;&lt; t.x;</p><p>  }</p><p>};</p><empty-line/><p>class Left : virtual public Top {</p><p>  int y;</p><p>protected:</p><p>  void specialPrint(ostream&amp; os) const {</p><p>    // Only print Left's part</p><p>    os &lt;&lt; ','&lt;&lt; y;</p><p>  }</p><p>public:</p><p>  Left(int m, int n) : Top(m) { y = n; }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Left&amp; l) {</p><p>    return os &lt;&lt; static_cast&lt;const Top&amp;&gt;(l) &lt;&lt; ',' &lt;&lt; l.y;</p><p>  }</p><p>};</p><empty-line/><p>class Right : virtual public Top {</p><p>  int z;</p><p>protected:</p><p>  void specialPrint(ostream&amp; os) const {</p><p>    // Only print Right's part</p><p>    os &lt;&lt; ','&lt;&lt; z;</p><p>  }</p><p>public:</p><p>  Right(int m, int n) : Top(m) { z = n; }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Right&amp; r) {</p><p>    return os &lt;&lt; static_cast&lt;const Top&amp;&gt;(r) &lt;&lt; ',' &lt;&lt; r.z;</p><p>  }</p><p>};</p><empty-line/><p>class Bottom : public Left, public Right {</p><p>  int w;</p><p>public:</p><p>  Bottom(int i, int j, int k, int m)</p><p>  : Top(i), Left(0, j), Right(0, k) { w = m; }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Bottom&amp; b) {</p><p>    os &lt;&lt; static_cast&lt;const Top&amp;&gt;(b);</p><p>    b.Left::specialPrint(os);</p><p>    b.Right::specialPrint(os);</p><p>    return os &lt;&lt; ',' &lt;&lt; b.w;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  Bottom b(1, 2, 3, 4);</p><p>  cout &lt;&lt; b &lt;&lt; endl;  // 1,2,3,4</p><p>} ///:<sup>~</sup></p><empty-line/><p>The <strong>specialPrint( )</strong> functions are <strong>protected</strong> since they will be called only by <strong>Bottom</strong>. They print only their own data and ignore their <strong>Top</strong> subobject, because the <strong>Bottom</strong> inserter is in control when these functions are called. The <strong>Bottom</strong> inserter must know about the virtual base, just as a <strong>Bottom</strong> constructor needs to. This same reasoning applies to assignment operators in a hierarchy with a virtual base, as well as to any function, member or not, that wants to share the work throughout all classes in the hierarchy<sup>.</sup></p><p>Having discussed virtual base classes, we can now illustrate the "full story" of object initialization. Since virtual bases give rise to shared subobjects, it makes sense that they should be available before the sharing takes place. Therefore, the order of initialization of subobjects follows these rules (recursively, as needed, of course)<sup>:</sup></p><p>3.All virtual base class subobjects are initialized, in top-down, left-to-right order according to where they appear in class definitions.</p><p>4.Non-virtual base classes are then initialized in the usual order.</p><p>5.All member objects are initialized in declaration order.</p><p>6.The complete object’s constructor executes.</p><p>The following program illustrates this behavior<sup>.</sup></p><p>//: C09:VirtInit.cpp</p><p>// Illustrates initialization order with virtual bases</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>class M {</p><p>public:</p><p>  M(const string&amp; s) {</p><p>    cout &lt;&lt; "M " &lt;&lt; s &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class A{</p><p>  M m;</p><p>public:</p><p>  A(const string&amp; s) : m("in A") {</p><p>     cout &lt;&lt; "A " &lt;&lt; s &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class B</p><p>{</p><p>  M m;</p><p>public:</p><p>  B(const string&amp; s) : m("in B")  {</p><p>    cout &lt;&lt; "B " &lt;&lt; s &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class C</p><p>{</p><p>  M m;</p><p>public:</p><p>  C(const string&amp; s) : m("in C")  {</p><p>    cout &lt;&lt; "C " &lt;&lt; s &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class D</p><p>{</p><p>  M m;</p><p>public:</p><p>  D(const string&amp; s) : m("in D") {</p><p>    cout &lt;&lt; "D " &lt;&lt; s &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class E : public A, virtual public B, virtual public C</p><p>{</p><p>  M m;</p><p>public:</p><p>  E(const string&amp; s)</p><p>  : A("from E"), B("from E"), C("from E"), m("in E") {</p><p>    cout &lt;&lt; "E " &lt;&lt; s &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class F : virtual public B, virtual public C, public D</p><p>{</p><p>  M m;</p><p>public:</p><p>  F(const string&amp; s)</p><p>  : B("from F"), C("from F"), D("from F"), m("in F") {</p><p>    cout &lt;&lt; "F " &lt;&lt; s &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class G : public E, public F</p><p>{</p><p>  M m;</p><p>public:</p><p>  G(const string&amp; s)</p><p>  : B("from G"), C("from G"), E("from G"),</p><p>    F("from G"), m("in G") {</p><p>    cout &lt;&lt; "G " &lt;&lt; s &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  G g("from main");</p><p>} ///:~</p><empty-line/><p>The classes in this code can be represented by the following diagram<sup>:</sup></p><p><image l:href="#13"/></p><empty-line/><p>Each class has an embedded member of type <strong>M</strong>. Note that only four derivations are virtual: <strong>E</strong> from <strong>B</strong> and <strong>C</strong>, and <strong>F</strong> from <strong>B</strong> and <strong>C</strong>. The output of this program is</p><p>M in B</p><p>B from G</p><p>M in C</p><p>C from G</p><p>M in A</p><p>A from E</p><p>M in E</p><p>E from G</p><p>M in D</p><p>D from F</p><p>M in F</p><p>F from G</p><p>M in G</p><p>G from main</p><empty-line/><p>The initialization of <strong>g</strong> requires its <strong>E</strong> and <strong>F</strong> part to first be initialized, but the <strong>B</strong> and <strong>C</strong> subobjects are initialized first, because they are virtual bases, and are initialized from <strong>G</strong>’s initializer, <strong>G</strong> being the most-derived class. The class <strong>B</strong> has no base classes, so according to rule 3, its member object <strong>m</strong> is initialized, then its constructor prints "<strong>B</strong> from <strong>G</strong>", and similarly for the <strong>C</strong> subject of <strong>E</strong>. The <strong>E</strong> subobject requires <strong>A</strong>, <strong>B</strong>, and <strong>C</strong> subobjects. Since <strong>B</strong> and <strong>C</strong> have already been initialized, the <strong>A</strong> subobject of the <strong>E</strong> subobject is initialized next, and then the <strong>E</strong> subobject itself. The same scenario repeats for <strong>g</strong>’s <strong>F</strong> subobject, but without duplicating the initialization of the virtual bases<sup>.</sup></p></section><section><title><p>Name lookup issues</p></title><p>The ambiguities we have illustrated with subobjects apply, of course, to any names, including function names. If a class has multiple direct base classes that share member functions of the same name, and you call one of those member functions, the compiler doesn’t know which one to choose. The following sample program would report such an error<sup>.</sup></p><p>// C09:AmbiguousName.cpp</p><p>class Top {};</p><empty-line/><p>class Left : virtual public Top {</p><p>public:</p><p>   void f(){}</p><p>};</p><empty-line/><p>class Right : virtual public Top {</p><p>public:</p><p>   void f(){}</p><p>};</p><empty-line/><p>class Bottom : public Left, public Right {};</p><empty-line/><p>int main() {</p><p>   Bottom b;</p><p>   b.f();     // error here</p><p>}</p><empty-line/><p>The class <strong>Bottom</strong> has inherited two functions of the same name (the signature is irrelevant, since name lookup occurs before overload resolution), and there is no way to choose between them. The usual technique to disambiguate the call is to qualify the function call with the base class name<sup>:</sup></p><p>//: C09:BreakTie.cpp</p><p>class Top {};</p><empty-line/><p>class Left : virtual public Top {</p><p>public:</p><p>   void f(){}</p><p>};</p><empty-line/><p>class Right : virtual public Top {</p><p>public:</p><p>   void f(){}</p><p>};</p><empty-line/><p>class Bottom : public Left, public Right {</p><p>public:</p><p>  using Left::f;</p><p>};</p><empty-line/><p>int main() {</p><p>   Bottom b;</p><p>   b.f();     // calls Left::f()</p><p>} ///:~</p><empty-line/><p>The name <strong>Left::f</strong> is now found in the scope of <strong>Bottom</strong>, so the name <strong>Right::f</strong> is not even considered. Of course, if you want to introduce extra functionality beyond what <strong>Left::f( )</strong> provides, you would implement a <strong>Bottom::f( )</strong> function that calls <strong>Left::f( )</strong>, in addition to other things<sup>.</sup></p><p>Functions with the same name occurring in different branches of a hierarchy often conflict. The following hierarchy has no such problem<sup>:</sup></p><p>//: C09:Dominance.cpp</p><p>class Top {</p><p>public:</p><p>  virtual void f() {}</p><p>};</p><empty-line/><p>class Left : virtual public Top {</p><p>public:</p><p>   void f(){}</p><p>};</p><empty-line/><p>class Right : virtual public Top {</p><p>};</p><empty-line/><p>class Bottom : public Left, public Right {};</p><empty-line/><p>int main() {</p><p>   Bottom b;</p><p>   b.f(); // calls Left::f()</p><p>} ///:~</p><empty-line/><p>In this case, there is no explicit <strong>Right::f( )</strong>, so <strong>Left::f( )</strong>, being the most derived, is chosen. Why? Well, pretend that <strong>Right</strong> did not exist, giving the single-inheritance hierarchy <strong>Top &lt;= Left &lt;= Bottom</strong>. You would certainly expect <strong>Left::f( )</strong> to be the function called by the expression <strong>b.f( )</strong>, because of normal scope rules (a derived class is considered a nested scope of a base class). In general, a name <strong>A::f</strong> is said to <emphasis>dominate</emphasis> the name <strong>B::f</strong> if <strong>A</strong> derives from <strong>B</strong>, directly or indirectly, or in other words, if <strong>A</strong> is "more derived" in the hierarchy than <strong>B</strong>.<a l:href="#n113" type="note">[113]</a> To summarize: in choosing between two functions with the same name, one of which dominates the other, the compiler chooses the one that dominates. If there is no dominant function, there is an ambiguity<sup>.</sup></p><p> The following program further illustrates the dominance principle<sup>.</sup></p><p>//: C09:Dominance2.cpp</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class A {</p><p>public:</p><p>   virtual void f() {cout &lt;&lt; "A::f\n";}</p><p>};</p><empty-line/><p>class B : virtual public A {</p><p>public:</p><p>   void f() {cout &lt;&lt; "B::f\n";}</p><p>};</p><empty-line/><p>class C : public B {};</p><p>class D : public C, virtual public A {};</p><empty-line/><p>int main()</p><p>{</p><p>   B* p = new D;</p><p>   p-&gt;f();  // calls B::f()</p><p>} ///:~</p><empty-line/><p>The class diagram for this hierarchy is as follows<sup>.</sup></p><p><image l:href="#14"/></p><empty-line/><p>The class <strong>A</strong> is a (direct, in this case) base class for <strong>B</strong>, and so the name <strong>B::f</strong> dominates <strong>A::f</strong><sup><strong>.</strong></sup></p></section><section><title><p>Avoiding MI</p></title><p>When the question of whether to use multiple inheritance comes up, ask at least two questions<sup>:</sup></p><p>1.Do you need to show the public interfaces of both these classes through your new type, or could one class be contained within the other, with only some of its interface exposed in the new class? </p><p>2.Do you need to upcast to both of the base classes? (This applies when you have more than two base classes, of course.<sup>)</sup></p><p>If you can answer "yes" to either question, you can avoid using MI and should probably do so<sup>.</sup></p><p>One situation to watch for is when one class needs to be upcast only as a function argument. In that case, the class can be embedded and an automatic type conversion operator provided in your new class to produce a reference to the embedded object. Any time you use an object of your new class as an argument to a function that expects the embedded object, the type conversion operator is used.<a l:href="#n114" type="note">[114]</a> However, type conversion can’t be used for normal member selection; that requires inheritance<sup>.</sup></p></section><section><title><p>Extending an interface</p></title><p>One of the best uses for multiple inheritance involves code that’s out of your control. Suppose you’ve acquired a library that consists of a header file and compiled member functions, but no source code for member functions. This library is a class hierarchy with virtual functions, and it contains some global functions that take pointers to the base class of the library; that is, it uses the library objects polymorphically. Now suppose you build an application around this library and write your own code that uses the base class polymorphically<sup>.</sup></p><p>Later in the development of the project or sometime during its maintenance, you discover that the base-class interface provided by the vendor doesn’t provide what you need: a function may be non-virtual and you need it to be virtual, or a virtual function is completely missing in the interface, but essential to the solution of your problem. Multiple inheritance is the perfect solution<sup>.</sup></p><p>For example, here’s the header file for a library you acquire<sup>:</sup></p><p>//: C09:Vendor.h</p><p>// Vendor-supplied class header</p><p>// You only get this &amp; the compiled Vendor.obj</p><p>#ifndef VENDOR_H</p><p>#define VENDOR_H</p><empty-line/><p>class Vendor {</p><p>public:</p><p>  virtual void v() const;</p><p>  void f() const;</p><p>  ~Vendor();</p><p>};</p><empty-line/><p>class Vendor1 : public Vendor {</p><p>public:</p><p>  void v() const;</p><p>  void f() const;</p><p>  ~Vendor1();</p><p>};</p><empty-line/><p>void A(const Vendor&amp;);</p><p>void B(const Vendor&amp;);</p><p>// Etc.</p><p>#endif // VENDOR_H ///:~</p><empty-line/><p>Assume the library is much bigger, with more derived classes and a larger interface. Notice that it also includes the functions <strong>A( )</strong> and <strong>B( )</strong>, which take a base reference and treat it polymorphically. Here’s the implementation file for the library<sup>:</sup></p><p>//: C09:Vendor.cpp {O}</p><p>// Implementation of VENDOR.H</p><p>// This is compiled and unavailable to you</p><p>#include &lt;iostream&gt;</p><p>#include "Vendor.h"</p><p>using namespace std;</p><empty-line/><p>void Vendor::v() const {</p><p>  cout &lt;&lt; "Vendor::v()\n";</p><p>}</p><p>void Vendor::f() const {</p><p>  cout &lt;&lt; "Vendor::f()\n";</p><p>}</p><p>Vendor::~Vendor() {</p><p>  cout &lt;&lt; "~Vendor()\n";</p><p>}</p><p>void Vendor1::v() const {</p><p>  cout &lt;&lt; "Vendor1::v()\n";</p><p>}</p><p>void Vendor1::f() const {</p><p>  cout &lt;&lt; "Vendor1::f()\n";</p><p>}</p><p>Vendor1::~Vendor1() {</p><p>  cout &lt;&lt; "~Vendor1()\n";</p><p>}</p><p>void A(const Vendor&amp; V) {</p><p>  // ...</p><p>  V.v();</p><p>  V.f();</p><p>  //..</p><p>}</p><p>void B(const Vendor&amp; V) {</p><p>  // ...</p><p>  V.v();</p><p>  V.f();</p><p>  //..</p><p>} ///:~</p><empty-line/><p>In your project, this source code is unavailable to you. Instead, you get a compiled file as <strong>Vendor.obj</strong> or <strong>Vendor.lib</strong> (or with the equivalent file suffixes for your system).</p><p>The problem occurs in the use of this library. First, the destructor isn’t virtual. In addition, <strong>f( )</strong> was not made virtual; we assume the library creator decided it wouldn’t need to be. And you discover that the interface to the base class is missing a function essential to the solution of your problem. Also suppose you’ve already written a fair amount of code using the existing interface (not to mention the functions <strong>A( )</strong> and <strong>B( ),</strong> which are out of your control), and you don’t want to change it.</p><p>To repair the problem, create your own class interface and multiply inherit a new set of derived classes from your interface and from the existing classes:</p><p>//: C09:Paste.cpp</p><p>//{L} Vendor</p><p>// Fixing a mess with MI</p><p>#include &lt;iostream&gt;</p><p>#include "Vendor.h"</p><p>using namespace std;</p><empty-line/><p>class MyBase { // Repair Vendor interface</p><p>public:</p><p>  virtual void v() const = 0;</p><p>  virtual void f() const = 0;</p><p>  // New interface function:</p><p>  virtual void g() const = 0;</p><p>  virtual ~MyBase() { cout &lt;&lt; "~MyBase()\n"; }</p><p>};</p><empty-line/><p>class Paste1 : public MyBase, public Vendor1 {</p><p>public:</p><p>  void v() const {</p><p>    cout &lt;&lt; "Paste1::v()\n";</p><p>    Vendor1::v();</p><p>  }</p><p>  void f() const {</p><p>    cout &lt;&lt; "Paste1::f()\n";</p><p>    Vendor1::f();</p><p>  }</p><p>  void g() const {</p><p>    cout &lt;&lt; "Paste1::g()\n";</p><p>  }</p><p>  ~Paste1() { cout &lt;&lt; "~Paste1()\n"; }</p><p>};</p><empty-line/><p>int main() {</p><p>  Paste1&amp; p1p = *new Paste1;</p><p>  MyBase&amp; mp = p1p; // Upcast</p><p>  cout &lt;&lt; "calling f()\n";</p><p>  mp.f();  // Right behavior</p><p>  cout &lt;&lt; "calling g()\n";</p><p>  mp.g(); // New behavior</p><p>  cout &lt;&lt; "calling A(p1p)\n";</p><p>  A(p1p); // Same old behavior</p><p>  cout &lt;&lt; "calling B(p1p)\n";</p><p>  B(p1p);  // Same old behavior</p><p>  cout &lt;&lt; "delete mp\n";</p><p>  // Deleting a reference to a heap object:</p><p>  delete &amp;mp; // Right behavior</p><p>} ///:~</p><empty-line/><p>In <strong>MyBase</strong> (which does <emphasis>not</emphasis> use MI), both <strong>f( )</strong> and the destructor are now virtual, and a new virtual function <strong>g( )</strong> is added to the interface. Now each of the derived classes in the original library must be re-created, mixing in the new interface with MI. The functions <strong>Paste1::v( )</strong> and <strong>Paste1::f( )</strong>need to call only the original base-class versions of their functions. But now, if you upcast to <strong>MyBase</strong> as in <strong>main( )</strong></p><p>MyBase* mp = p1p; // Upcast</p><p>any function calls made through <strong>mp</strong> will be polymorphic, including <strong>delete</strong>. Also, the new interface function <strong>g( )</strong> can be called through <strong>mp</strong>. Here’s the output of the program:</p><p>calling f()</p><p>Paste1::f()</p><p>Vendor1::f()</p><p>calling g()</p><p>Paste1::g()</p><p>calling A(p1p)</p><p>Paste1::v()</p><p>Vendor1::v()</p><p>Vendor::f()</p><p>calling B(p1p)</p><p>Paste1::v()</p><p>Vendor1::v()</p><p>Vendor::f()</p><p>delete mp</p><p>~Paste1()</p><p>~Vendor1()</p><p>~Vendor()</p><p>~MyBase()</p><empty-line/><p>The original library functions <strong>A( )</strong> and <strong>B( )</strong> still work the same (assuming the new <strong>v( )</strong> calls its base-class version). The destructor is now virtual and exhibits the correct behavior.</p><p>Although this is a messy example, it does occur in practice, and it’s a good demonstration of where multiple inheritance is clearly necessary: You must be able to upcast to both base classes.</p></section><section><title><p>Summary</p></title><p>One reason MI exists in C++ is that it is a hybrid language and couldn’t enforce a single monolithic class hierarchy the way Smalltalk and Java do. Instead, C++ allows many inheritance trees to be formed, so sometimes you may need to combine the interfaces from two or more trees into a new class.</p><p>If no "diamonds" appear in your class hierarchy, MI is fairly simple (although identical function signatures in base classes must still be resolved). If a diamond appears, you may want to eliminate duplicate subobjects by introducing virtual base classes. This not only adds confusion, but the underlying representation becomes more complex and less efficient.</p><p>Multiple inheritance has been called the "goto of the ’90s."<a l:href="#n115" type="note">[115]</a> This seems appropriate because, like a goto, MI is best avoided in normal programming, but can occasionally be very useful. It’s a "minor" but more advanced feature of C++, designed to solve problems that arise in special situations. If you find yourself using it often, you might want to take a look at your reasoning. A good Occam’s Razor is to ask, "Must I upcast to all the base classes?" If not, your life will be easier if you embed instances of all the classes you <emphasis>don’t</emphasis> need to upcast to.</p></section><section><title><p>Exercises</p></title><p>These exercises will take you step by step through the complexities of MI.</p><p>             1.             Create a base class <strong>X</strong> with a single constructor that takes an <strong>int</strong> argument and a member function <strong>f( )</strong>, which takes no arguments and returns <strong>void</strong>. Now derive <strong>Y</strong> and <strong>Z</strong> from <strong>X</strong>, creating constructors for each of them that take a single <strong>int</strong> argument. Now derive <strong>A</strong> from <strong>Y</strong> and <strong>Z</strong>. Create an object of class <strong>A</strong>, and call <strong>f( )</strong> for that object. Fix the problem with explicit disambiguation.</p><p>        60.             Starting with the results of exercise 1, create a pointer to an <strong>X</strong> called <strong>px</strong>, and assign to it the address of the object of type <strong>A</strong> you created before. Fix the problem using a virtual base class. Now fix <strong>X</strong> so you no longer have to call the constructor for <strong>X</strong> inside <strong>A</strong>.</p><p>         61.             Starting with the results of exercise 2, remove the explicit disambiguation for <strong>f( )</strong>, and see if you can call <strong>f( )</strong> through <strong>px</strong>. Trace it to see which function gets called. Fix the problem so the correct function will be called in a class hierarchy.</p><empty-line/></section></section><section><title><p>10: Design patterns</p></title><section><p>"… describe a problem which occurs over and over again in our environment, and then describe the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice" —Christopher Alexander</p><p>This chapter introduces the important and yet nontraditional "patterns" approach to program design.</p><p>In recent times, the most important step forward in object-oriented design is probably the "design patterns" movement, chronicled in <emphasis>Design Patterns</emphasis>, by Gamma, Helm, Johnson &amp; Vlissides (Addison-Wesley, 1995).<a l:href="#n116" type="note">[116]</a> That book shows 23 solutions to particular classes of problems. In this chapter, we discuss the basic concepts of design patterns and provide code examples that illustrate selected patterns. This should whet your appetite for reading <emphasis>Design Patterns</emphasis> (a source of what has now become an essential, almost mandatory vocabulary for object-oriented programming)<sup>.</sup></p></section><section><title><p>The pattern concept</p></title><p>Initially, you can think of a pattern as an especially clever and insightful way to solve a particular class of problems. That is, it looks like a lot of people have worked out all the angles of a problem and have come up with the most general, flexible solution for that type of problem. The problem could be one you have seen and solved before, but your solution probably didn’t have the kind of completeness you’ll see embodied in a pattern. Furthermore, the pattern exists independently of any particular implementation and, indeed, can be implemented in a number of ways<sup>.</sup></p><p>Although they’re called "design patterns," they really aren’t tied to the realm of design. A pattern seems to stand apart from the traditional way of thinking about analysis, design, and implementation. Instead, a pattern embodies a complete idea within a program, and thus it can sometimes also span the analysis phase and high-level design phase. Because a pattern has a direct implementation in code, you might not expect it to show up before low-level design or implementation (and in fact you might not realize that you need a particular pattern until you get to those phases)<sup>.</sup></p><p>The basic concept of a pattern can also be seen as the basic concept of program design in general: adding layers of abstraction. Whenever you abstract something, you’re isolating particular details, and one of the most compelling motivations for this is to <emphasis>separate things that change from things that stay the same</emphasis>. Another way to put this is that once you find some part of your program that’s likely to change for one reason or another, you’ll want to keep those changes from propagating other modifications throughout your code. Not only does this make the code easier to maintain, but it also renders code easier to read and understand (which invariably results in lowered costs over time)<sup>.</sup></p><p>The most difficult part of developing an elegant and maintainable design is often discovering what we call "the vector of change." (Here, "vector" refers to the maximum gradient as understood in the sciences, and not a container class.) This means finding the most important thing that changes in your system or, put another way, discovering where your greatest cost is. Once you discover the vector of change, you have the focal point around which to structure your design<sup>.</sup></p><p>So the goal of design patterns is to isolate changes in your code; to put it another way: <emphasis>discover what changes and encapsulate it</emphasis>. If you look at it this way, you’ve been seeing some design patterns already in this book. For example, inheritance could be thought of as a design pattern (albeit one implemented by the compiler). It allows you to express differences in behavior (that’s the thing that changes) in objects that all have the same interface (that’s what stays the same). Composition could also be considered a pattern, since it allows you to change—dynamically or statically—the objects that implement your class, and thus the way that class works. Normally, however, features that are directly supported by a programming language have not been classified as design patterns<sup>.</sup></p><p>You’ve also already seen another pattern that appears in <emphasis>Design Patterns</emphasis>: the <emphasis>iterator</emphasis>. This is the fundamental tool used in the design of the STL, described earlier in this book. The iterator hides the particular implementation of the container as you’re stepping through and selecting the elements one by one. Iterators allow you to write generic code that performs an operation on all the elements in a range without regard to the container that holds the range. Thus, your generic code can be used with any container that can produce iterators<sup>.</sup></p></section><section><title><p>The Singleton</p></title><section><p>Possibly the simplest design pattern is the <emphasis>Singleton</emphasis>, which is a way to provide one and only one instance of a class. For example, if a class controls a Singleton resource, you only want to allow one instance of that class. The following program shows how to implement a Singleton object in C++:</p><p>//: C10:SingletonPattern.cpp</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Singleton {</p><p>  static Singleton s;</p><p>  int i;</p><p>  Singleton(int x) : i(x) { }</p><p>  Singleton&amp; operator=(Singleton&amp;);  // Disallowed</p><p>  Singleton(const Singleton&amp;);       // Disallowed</p><p>public:</p><p>  static Singleton&amp; instance() {</p><p>    return s;</p><p>  }</p><p>  int getValue() { return i; }</p><p>  void setValue(int x) { i = x; }</p><p>};</p><empty-line/><p>Singleton Singleton::s(47);</p><empty-line/><p>int main() {</p><p>  Singleton&amp; s = Singleton::instance();</p><p>  cout &lt;&lt; s.getValue() &lt;&lt; endl;</p><p>  Singleton&amp; s2 = Singleton::instance();</p><p>  s2.setValue(9);</p><p>  cout &lt;&lt; s.getValue() &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>The key to creating a Singleton is to prevent the client programmer from having any control over the lifetime of the object. To do this, declare all constructors <strong>private</strong>, and prevent the compiler from implicitly generating any constructors. Note that the copy constructor and assignment operator are declared private to prevent any sort of copies being made<sup>.</sup></p><p>You must also decide how you’re going to create the object. Here, it’s created statically, but you can also wait until the client programmer asks for one and create it on demand. This is called <emphasis>lazy initialization</emphasis>, and it only makes sense if your object is expensive to create and if it might not always be needed.</p><p>If you return a pointer instead of a reference, the user could inadvertently delete the pointer, so the implementation above is considered safest. In any case, the object should be stored privately. </p><p>You provide access through public member functions. Here, <strong>instance( )</strong> produces a reference to the <strong>Singleton</strong> object. The rest of the interface (<strong>getValue( )</strong> and <strong>setValue( )</strong>) is the regular class interface<sup>.</sup></p><p>Note that you aren’t restricted to creating only one object. This technique easily supports the creation of a limited pool of objects. In that situation, however, you can be confronted with the problem of sharing objects in the pool. If this is an issue, you can create a solution involving a check-out and check-in of the shared objects<sup>.</sup></p></section><section><title><p>Variations on Singleton</p></title><p>Any <strong>static</strong> member object inside a class is an expression of Singleton: one and only one will be made. So in a sense, the language has direct support for the idea; we certainly use it on a regular basis. However, a problem is associated with <strong>static</strong> objects (member or not), and that’s the order of initialization, as described in Volume 1 of this book. If one <strong>static</strong> object depends on another, it’s important that the objects are initialized in the correct order<sup>.</sup></p><p>In Volume 1, you were shown how to control initialization order by defining a static object inside a function. This delays the initialization of the object until the first time the function is called. If the function returns a reference to the static object, it gives you the effect of a Singleton while removing much of the worry of static initialization. For example, suppose you want to create a log file upon the first call to a function that returns a reference to that log file. This header file will do the trick<sup>:</sup></p><p>//: C10:LogFile.h</p><p>#ifndef LOGFILE_H</p><p>#define LOGFILE_H</p><p>#include &lt;fstream&gt;</p><empty-line/><p>std::ofstream&amp; logfile();</p><empty-line/><p>#endif // LOGFILE_H ///:~</p><empty-line/><p>The implementation <emphasis>must not be inlined</emphasis>, because that would mean that the whole function, including the static object definition within, could be duplicated in any translation unit where it’s included, which violates C++’s one-definition rule.<a l:href="#n117" type="note">[117]</a> This would most certainly foil the attempts to control the order of initialization (but potentially in a subtle and hard-to-detect fashion). So the implementation must be separate<sup>:</sup></p><p>//: C10:LogFile.cpp {O}</p><p>#include "LogFile.h"</p><p>std::ofstream&amp; logfile() {</p><p>  static std::ofstream log("Logfile.log");</p><p>  return log;</p><p>} ///:~</p><empty-line/><p>Now the <strong>log</strong> object will not be initialized until the first time <strong>logfile( )</strong> is called. So if you create a function<sup>:</sup></p><p>//: C10:UseLog1.h</p><p>#ifndef USELOG1_H</p><p>#define USELOG1_H</p><p>void f();</p><p>#endif // USELOG1_H ///:~</p><empty-line/><p>that uses <strong>logfile()</strong> in its implementation:</p><p>//: C10:UseLog1.cpp {O}</p><p>#include "UseLog1.h"</p><p>#include "LogFile.h"</p><p>void f() {</p><p>  logfile() &lt;&lt; __FILE__ &lt;&lt; std::endl;</p><p>} ///:~</p><empty-line/><p>And you use <strong>logfile() </strong>again in another file:</p><p>//: C10:UseLog2.cpp</p><p>//{L} LogFile UseLog1</p><p>#include "UseLog1.h"</p><p>#include "LogFile.h"</p><p>using namespace std;</p><p>void g() {</p><p>  logfile() &lt;&lt; __FILE__ &lt;&lt; endl;</p><p>}</p><empty-line/><p>int main() {</p><p>  f();</p><p>  g();</p><p>} ///:~</p><empty-line/><p>the <strong>log </strong>object doesn’t get created until the first call to <strong>f( )</strong>.</p><p>You can easily combine the creation of the static object inside a member function with the Singleton class. <strong>SingletonPattern.cpp</strong> can be modified to use this approach:<a l:href="#n118" type="note">[118]</a></p><p>//: C10:SingletonPattern2.cpp</p><p>// Meyers’ Singleton</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Singleton {</p><p>  int i;</p><p>  Singleton(int x) : i(x) { }</p><p>  void operator=(Singleton&amp;);</p><p>  Singleton(const Singleton&amp;);</p><p>public:</p><p>  static Singleton&amp; instance() {</p><p>    static Singleton s(47);</p><p>    return s;</p><p>  }</p><p>  int getValue() { return i; }</p><p>  void setValue(int x) { i = x; }</p><p>};</p><empty-line/><p>int main() {</p><p>  Singleton&amp; s = Singleton::instance();</p><p>  cout &lt;&lt; s.getValue() &lt;&lt; endl;</p><p>  Singleton&amp; s2 = Singleton::instance();</p><p>  s2.setValue(9);</p><p>  cout &lt;&lt; s.getValue() &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>An especially interesting case occurs if two Singletons depend on each other, like this:</p><p>//: C10:FunctionStaticSingleton.cpp</p><p>class Singleton1 {</p><p>  Singleton1() {}</p><p>public:</p><p>  static Singleton1&amp; ref() {</p><p>    static Singleton1 single;</p><p>    return single;</p><p>  }</p><p>};</p><empty-line/><p>class Singleton2 {</p><p>  Singleton1&amp; s1;</p><p>  Singleton2(Singleton1&amp; s) : s1(s) {}</p><p>public:</p><p>  static Singleton2&amp; ref() {</p><p>    static Singleton2 single(Singleton1::ref());</p><p>    return single;</p><p>  }</p><p>  Singleton1&amp; f() { return s1; }</p><p>};</p><empty-line/><p>int main() {</p><p>  Singleton1&amp; s1 = Singleton2::ref().f();</p><p>} ///:~</p><empty-line/><p>When <strong>Singleton2::ref( )</strong> is called, it causes its sole <strong>Singleton2</strong> object to be created. In the process of this creation, <strong>Singleton1::ref( )</strong> is called, and that causes the sole <strong>Singleton1</strong> object to be created. Because this technique doesn’t rely on the order of linking or loading, the programmer has much better control over initialization, leading to fewer problems<sup>.</sup></p><p>Yet another variation on Singleton allows you to separate the "Singleton-ness" of an object from its implementation. This is achieved through templates, using the Curiously Recurring Template Pattern mentioned in Chapter 5<sup>.</sup></p><p>//: C10:CuriousSingleton.cpp</p><p>// Separates a class from its Singleton-ness (almost)</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>template&lt;class T&gt;</p><p>class Singleton {</p><p>public:</p><p>  static T&amp; instance() {</p><p>    static T theInstance;</p><p>    return theInstance;</p><p>  }</p><p>protected:</p><p>  Singleton() {}</p><p>  virtual ~Singleton() {}</p><p>private:</p><p>  Singleton(const Singleton&amp;);</p><p>  Singleton&amp; operator=(const Singleton&amp;);</p><p>};</p><empty-line/><p>// A sample class to be made into a Singleton</p><p>class MyClass : public Singleton&lt;MyClass&gt; {</p><p>  int x;</p><p>protected:</p><p>  friend class Singleton&lt;MyClass&gt;;</p><p>  MyClass(){x = 0;}</p><p>public:</p><p>  void setValue(int n) { x = n; }</p><p>  int getValue() const { return x; }</p><p>};</p><empty-line/><p>int main() {</p><p>  MyClass&amp; m = MyClass::instance();</p><p>  cout &lt;&lt; m.getValue() &lt;&lt; endl;</p><p>  m.setValue(1);</p><p>  cout &lt;&lt; m.getValue() &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p><strong>MyClass</strong> is made a Singleton by:</p><p>1.       Making its constructor private or protected.</p><p>2.      Making <strong>Singleton&lt;MyClass&gt;</strong> a friend.</p><p>3.      Deriving <strong>MyClass</strong> from <strong>Singleton&lt;MyClass&gt;</strong>.</p><p>The self-referencing in step 3 may sound implausible, but as we explained in Chapter 5, it works because there is only a static data dependency on the template argument in the <strong>Singleton</strong> template. In other words, the code for the class <strong>Singleton&lt;MyClass&gt;</strong> can be instantiated by the compiler because it is not dependent on the size of <strong>MyClass</strong>. It’s only later, when <strong>Singleton&lt;MyClass&gt;::instance( )</strong> is first called, that the size of <strong>MyClass</strong> is needed, and of course by then compilation of <strong>MyClass</strong> is complete and its size is known.<a l:href="#n119" type="note">[119]</a></p><p>It’s interesting how intricate implementing such a simple pattern as Singleton can be. We haven’t even addressed issues of thread safety, and yet many pages have elapsed since the beginning of this section. The last thing we wish to say about Singleton is that it should be used sparingly. True Singleton objects arise rarely, and the last thing a Singleton should be used for is to replace a global variable.<a l:href="#n120" type="note">[120]</a></p></section></section><section><title><p>Classifying patterns</p></title><section><p><emphasis>Design Patterns</emphasis> discusses 23 patterns, classified under three purposes (all of which revolve around the particular aspect that can vary):</p><p>1.<strong>Creational</strong>: how an object can be created. This often involves isolating the details of object creation so your code isn’t dependent on what types of objects there are and thus doesn’t have to be changed when you add a new type of object. The aforementioned Singleton is classified as a creational pattern, and later in this chapter you’ll see examples of Factory Method<sup>.</sup></p><p>2.<strong>Structural</strong>: designing objects to satisfy particular project constraints. These affect the way objects are connected with other objects to ensure that changes in the system don’t require changes to those connections<sup>.</sup></p><p>3.<strong>Behavioral</strong>: objects that handle particular types of actions within a program. These encapsulate processes that you want to perform, such as interpreting a language, fulfilling a request, moving through a sequence (as in an iterator), or implementing an algorithm. This chapter contains examples of the Observer and the Visitor patterns<sup>.</sup></p><p><emphasis>Design Patterns</emphasis> includes a section on each of its 23 patterns along with one or more examples for each, typically in C++ but sometimes in Smalltalk. This book will not repeat all the details of the patterns shown in <emphasis>Design Patterns</emphasis> since that book stands on its own and should be studied separately. The catalog and examples provided here are intended to rapidly give you a grasp of the patterns, so you can get a decent feel for what patterns are about and why they are so important<sup>.</sup></p></section><section><title><p>Features, idioms, patterns</p></title><p>Work is continuing beyond what is in the GoF book, of course; hence, there are more patterns and a more refined process on defining design patterns in general.<a l:href="#n121" type="note">[121]</a> This is important because it is not easy to identify new patterns or to properly describe them. There is some confusion in the popular literature on what a design pattern is, for example. Patterns are not trivial nor are they typically represented by features that are built into a programming language. Constructors and destructors, for example, could be called the "guaranteed initialization and cleanup design pattern." These are important and essential constructs, but they’re routine language constructs and are not rich enough to be considered a design pattern<sup>.</sup></p><p>Another non-example comes from various forms of aggregation. Aggregation is a completely fundamental principle in object-oriented programming: you make objects out of other objects. Yet sometimes this idea is erroneously classified as a pattern. This is unfortunate because it pollutes the idea of the design pattern and suggests that anything that surprises you the first time you see it should be made into a design pattern<sup>.</sup></p><p>Yet another misguided example is found in the Java language; the designers of the JavaBeans specification decided to refer to the simple "get/set" naming convention as a design pattern (for example, <strong>getInfo( )</strong> returns an <strong>Info</strong> property and <strong>setInfo( )</strong> changes it). This is just a commonplace naming convention and in no way constitutes a design pattern<sup>.</sup></p></section></section><section><title><p>Building complex objects</p></title><p>The class that will be created in the next example models a bicycle that can have a choice of parts, according to its type (mountain bike, touring bike, or racing bike). This is called the <strong>Builder</strong> design pattern. A builder class is associated with each flavor of bicycle, each of which implements the interface specified in the abstract class <strong>BicycleBuilder</strong>. A separate class, <strong>BicycleTechnician</strong>, uses a concrete <strong>BicycleBuilder</strong> object to construct a <strong>Bicycle</strong> object<sup>.</sup></p><p>//: C10:Bicycle.h</p><p>// Defines classes to build bicycles</p><p>// Illustrates the Builder Design Pattern</p><p>#ifndef BICYCLE_H</p><p>#define BICYCLE_H</p><empty-line/><p>#include &lt;iosfwd&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><empty-line/><p>class BicyclePart {</p><p>public:</p><p>  enum BPart {FRAME, WHEEL, SEAT, DERAILLEUR,</p><p>    HANDLEBAR, SPROCKET, RACK, SHOCK, NPARTS};</p><p>  BicyclePart(BPart);</p><p>  friend std::ostream&amp;</p><p>  operator&lt;&lt;(std::ostream&amp;, const BicyclePart&amp;);</p><p>private:</p><p>  BPart id;</p><p>  static std::string names[NPARTS];</p><p>};</p><empty-line/><p>class Bicycle {</p><p>public:</p><p>  ~Bicycle();</p><p>  void addPart(BicyclePart*);</p><p>  friend std::ostream&amp;</p><p>  operator&lt;&lt;(std::ostream&amp;, const Bicycle&amp;);</p><p>private:</p><p>  std::vector&lt;BicyclePart*&gt; parts;</p><p>};</p><empty-line/><p>class BicycleBuilder {</p><p>public:</p><p>  BicycleBuilder() {</p><p>    product = 0;</p><p>  }</p><p>  void createProduct() {</p><p>    product = new Bicycle;</p><p>  }</p><p>  virtual void buildFrame() = 0;</p><p>  virtual void buildWheel() = 0;</p><p>  virtual void buildSeat() = 0;</p><p>  virtual void buildDerailleur() = 0;</p><p>  virtual void buildHandlebar() = 0;</p><p>  virtual void buildSprocket() = 0;</p><p>  virtual void buildRack() = 0;</p><p>  virtual void buildShock() = 0;</p><p>  virtual std::string getBikeName() const = 0;</p><p>  Bicycle* getProduct() {</p><p>    Bicycle* temp = product;</p><p>    product = 0;  // relinquish product</p><p>    return temp;</p><p>  }</p><p>protected:</p><p>  Bicycle* product;</p><p>};</p><empty-line/><p>class MountainBikeBuilder : public BicycleBuilder {</p><p>public:</p><p>  void buildFrame();</p><p>  void buildWheel();</p><p>  void buildSeat();</p><p>  void buildDerailleur();</p><p>  void buildHandlebar();</p><p>  void buildSprocket();</p><p>  void buildRack();</p><p>  void buildShock();</p><p>  std::string getBikeName() const {</p><p>    return "MountainBike";</p><p>  }</p><p>};</p><empty-line/><p>class TouringBikeBuilder : public BicycleBuilder {</p><p>public:</p><p>  void buildFrame();</p><p>  void buildWheel();</p><p>  void buildSeat();</p><p>  void buildDerailleur();</p><p>  void buildHandlebar();</p><p>  void buildSprocket();</p><p>  void buildRack();</p><p>  void buildShock();</p><p>  std::string getBikeName() const {</p><p>    return "TouringBike";</p><p>  }</p><p>};</p><empty-line/><p>class RacingBikeBuilder : public BicycleBuilder {</p><p>public:</p><p>  void buildFrame();</p><p>  void buildWheel();</p><p>  void buildSeat();</p><p>  void buildDerailleur();</p><p>  void buildHandlebar();</p><p>  void buildSprocket();</p><p>  void buildRack();</p><p>  void buildShock();</p><p>  std::string getBikeName() const {</p><p>    return "RacingBike";</p><p>  }</p><p>};</p><empty-line/><p>class BicycleTechnician {</p><p>public:</p><p>  BicycleTechnician() {</p><p>    builder = 0;</p><p>  }</p><p>  void setBuilder(BicycleBuilder* b) {</p><p>    builder = b;</p><p>  }</p><p>  void construct();</p><p>private:</p><p>  BicycleBuilder* builder;</p><p>};</p><empty-line/><p>#endif ///:~</p><empty-line/><p>A <strong>Bicycle</strong> holds a vector of pointers to <strong>BicyclePart</strong> representing the parts used to construct the bicycle. To initiate the construction of a bicycle, a technician calls <strong>BicycleBuilder::createproduct( )</strong> on a derived <strong>BicycleBuilder</strong> object. The <strong>BicycleTechnician::construct( )</strong> function calls all the functions in the <strong>BicycleBuilder</strong> interface (since it doesn’t know what type of concrete builder it has). The concrete builder classes omit (via empty function bodies) those actions that do not apply to the type of bicycle they build, as you can see in the following implementation file<sup>.</sup></p><p>//: C10:Bicycle.cpp {O}</p><p>// Defines classes to build bicycles</p><p>// Illustrates the Builder Design Pattern</p><p>#include &lt;cassert&gt;</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "Bicycle.h"</p><p>#include "../purge.h"</p><p>using namespace std;</p><empty-line/><p>// BicyclePart implementation</p><p>BicyclePart::BicyclePart(BPart bp) {</p><p>  id = bp;</p><p>}</p><p>ostream&amp;</p><p>operator&lt;&lt;(ostream&amp; os, const BicyclePart&amp; bp) {</p><p>  return os &lt;&lt; bp.names[bp.id];</p><p>}</p><p>std::string BicyclePart::names[NPARTS] = {</p><p>  "Frame", "Wheel", "Seat", "Derailleur",</p><p>  "Handlebar", "Sprocket", "Rack", "Shock"};</p><empty-line/><p>// Bicycle implementation</p><p>Bicycle::~Bicycle() {</p><p>  purge(parts);</p><p>}</p><p>void Bicycle::addPart(BicyclePart* bp) {</p><p>  parts.push_back(bp);</p><p>}</p><p>ostream&amp;</p><p>operator&lt;&lt;(ostream&amp; os, const Bicycle&amp; b) {</p><p>  os &lt;&lt; "{ ";</p><p>  for (size_t i = 0; i &lt; b.parts.size(); ++i)</p><p>    os &lt;&lt; *b.parts[i] &lt;&lt; ' ';</p><p>  return os &lt;&lt; '}';</p><p>}</p><empty-line/><p>// MountainBikeBuilder implementation</p><p>void MountainBikeBuilder::buildFrame() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::FRAME));</p><p>}</p><p>void MountainBikeBuilder::buildWheel() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::WHEEL));</p><p>}</p><p>void MountainBikeBuilder::buildSeat() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::SEAT));</p><p>}</p><p>void MountainBikeBuilder::buildDerailleur() {</p><p>  product-&gt;addPart(</p><p>    new BicyclePart(BicyclePart::DERAILLEUR));</p><p>}</p><p>void MountainBikeBuilder::buildHandlebar() {</p><p>  product-&gt;addPart(</p><p>    new BicyclePart(BicyclePart::HANDLEBAR));</p><p>}</p><p>void MountainBikeBuilder::buildSprocket() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::SPROCKET));</p><p>}</p><p>void MountainBikeBuilder::buildRack() {}</p><p>void MountainBikeBuilder::buildShock() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::SHOCK));</p><p>}</p><empty-line/><p>// TouringBikeBuilder implementation</p><p>void TouringBikeBuilder::buildFrame() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::FRAME));</p><p>}</p><p>void TouringBikeBuilder::buildWheel() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::WHEEL));</p><p>}</p><p>void TouringBikeBuilder::buildSeat() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::SEAT));</p><p>}</p><p>void TouringBikeBuilder::buildDerailleur() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::DERAILLEUR));</p><p>}</p><p>void TouringBikeBuilder::buildHandlebar() {</p><p>  product-&gt;addPart(</p><p>    new BicyclePart(BicyclePart::HANDLEBAR));</p><p>}</p><p>void TouringBikeBuilder::buildSprocket() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::SPROCKET));</p><p>}</p><p>void TouringBikeBuilder::buildRack() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::RACK));</p><p>}</p><p>void TouringBikeBuilder::buildShock() {}</p><empty-line/><p>// RacingBikeBuilder implementation</p><p>void RacingBikeBuilder::buildFrame() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::FRAME));</p><p>}</p><p>void RacingBikeBuilder::buildWheel() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::WHEEL));</p><p>}</p><p>void RacingBikeBuilder::buildSeat() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::SEAT));</p><p>}</p><p>void RacingBikeBuilder::buildDerailleur() {}</p><p>void RacingBikeBuilder::buildHandlebar() {</p><p>  product-&gt;addPart(</p><p>    new BicyclePart(BicyclePart::HANDLEBAR));</p><p>}</p><p>void RacingBikeBuilder::buildSprocket() {</p><p>  product-&gt;addPart(new BicyclePart(BicyclePart::SPROCKET));</p><p>}</p><p>void RacingBikeBuilder::buildRack() {}</p><p>void RacingBikeBuilder::buildShock() {}</p><empty-line/><p>// BicycleTechnician implementation</p><p>void BicycleTechnician::construct()</p><p>{</p><p>  assert(builder);</p><p>  builder-&gt;createProduct();</p><p>  builder-&gt;buildFrame();</p><p>  builder-&gt;buildWheel();</p><p>  builder-&gt;buildSeat();</p><p>  builder-&gt;buildDerailleur();</p><p>  builder-&gt;buildHandlebar();</p><p>  builder-&gt;buildSprocket();</p><p>  builder-&gt;buildRack();</p><p>  builder-&gt;buildShock();</p><p>}; ///:~</p><empty-line/><p>The <strong>Bicycle</strong> stream inserter calls the corresponding inserter for each <strong>BicyclePart</strong>, and that prints its type name so that you can see what a <strong>Bicycle</strong> contains. The power of this pattern is that it separates the algorithm for assembling parts into a complete product from the parts themselves and allows different algorithms for different products via different implementations of a common interface. Here is a sample program, along with the resulting output, that uses these classes<sup>.</sup></p><p>//: C10:BuildBicycles.cpp</p><p>//{L} Bicycle</p><p>#include &lt;cstddef&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;map&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../purge.h"</p><p>#include "Bicycle.h"</p><p>using namespace std;</p><empty-line/><p>// Constructs a bike via a concrete builder</p><p>Bicycle*</p><p>buildMeABike(BicycleTechnician&amp; t, BicycleBuilder* builder) {</p><p>  t.setBuilder(builder);</p><p>  t.construct();</p><p>  Bicycle* b = builder-&gt;getProduct();</p><p>  cout &lt;&lt; "Built a " &lt;&lt; builder-&gt;getBikeName() &lt;&lt; endl;</p><p>  return b;</p><p>}</p><empty-line/><p>int main() {</p><p>  // Create an order for some bicycles</p><p>  map &lt;string, size_t&gt; order;</p><p>  order["mountain"] = 2;</p><p>  order["touring"] = 1;</p><p>  order["racing"] = 3;</p><empty-line/><p>  // Build bikes</p><p>  vector&lt;Bicycle*&gt; bikes;</p><p>  BicycleBuilder* m = new MountainBikeBuilder;</p><p>  BicycleBuilder* t = new TouringBikeBuilder;</p><p>  BicycleBuilder* r = new RacingBikeBuilder;</p><p>  BicycleTechnician tech;</p><p>  map&lt;string, size_t&gt;::iterator it = order.begin();</p><p>  while (it != order.end()) {</p><p>    BicycleBuilder* builder;</p><p>    if (it-&gt;first == "mountain")</p><p>      builder = m;</p><p>    else if (it-&gt;first == "touring")</p><p>      builder = t;</p><p>    else if (it-&gt;first == "racing")</p><p>      builder = r;</p><p>    for (size_t i = 0; i &lt; it-&gt;second; ++i)</p><p>      bikes.push_back(buildMeABike(tech, builder));</p><p>    ++it;</p><p>  }</p><p>  delete m;</p><p>  delete t;</p><p>  delete r;</p><empty-line/><p>  // Display inventory</p><p>  for (size_t i = 0; i &lt; bikes.size(); ++i)</p><p>    cout &lt;&lt; "Bicycle: " &lt;&lt; *bikes[i] &lt;&lt; endl;</p><p>  purge(bikes);</p><p>}</p><empty-line/><p>/* Output:</p><p>Built a MountainBike</p><p>Built a MountainBike</p><p>Built a RacingBike</p><p>Built a RacingBike</p><p>Built a RacingBike</p><p>Built a TouringBike</p><p>Bicycle: { Frame Wheel Seat Derailleur Handlebar Sprocket Shock }</p><p>Bicycle: { Frame Wheel Seat Derailleur Handlebar Sprocket Shock }</p><p>Bicycle: { Frame Wheel Seat Handlebar Sprocket }</p><p>Bicycle: { Frame Wheel Seat Handlebar Sprocket }</p><p>Bicycle: { Frame Wheel Seat Handlebar Sprocket }</p><p>Bicycle: { Frame Wheel Seat Derailleur Handlebar Sprocket Rack } */ ///:<sup>~</sup></p><empty-line/></section><section><title><p>Factories: encapsulating object creation</p></title><section><p>When you discover that you need to add new types to a system, the most sensible first step is to use polymorphism to create a common interface to those new types. This separates the rest of the code in your system from the knowledge of the specific types that you are adding. New types can be added without disturbing existing code … or so it seems. At first it would appear that you need to change the code in such a design only in the place where you inherit a new type, but this is not quite true. You must still create an object of your new type, and at the point of creation you must specify the exact constructor to use. Thus, if the code that creates objects is distributed throughout your application, you have the same problem when adding new types—you must still chase down all the points of your code where type matters. It happens to be the <emphasis>creation</emphasis> of the type that matters in this case rather than the <emphasis>use</emphasis> of the type (which is taken care of by polymorphism), but the effect is the same: adding a new type can cause problems<sup>.</sup></p><p>The solution is to force the creation of objects to occur through a common <emphasis>factory</emphasis> rather than to allow the creational code to be spread throughout your system. If all the code in your program must go through this factory whenever it needs to create one of your objects, all you must do when you add a new object is modify the factory. This design is a variation of the pattern commonly known as <emphasis>Factory Method</emphasis>. Since every object-oriented program creates objects, and since it’s likely you will extend your program by adding new types, factories may be the most useful of all design patterns<sup>.</sup></p><p>As an example, let’s revisit the <strong>Shape</strong> system. One approach to implementing a factory is to define a <strong>static</strong> member function in the base class:</p><p>//: C10:ShapeFactory1.cpp</p><p>#include &lt;iostream&gt;</p><p>#include &lt;stdexcept&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../purge.h"</p><p>using namespace std;</p><empty-line/><p>class Shape {</p><p>public:</p><p>  virtual void draw() = 0;</p><p>  virtual void erase() = 0;</p><p>  virtual ~Shape() {}</p><p>  class BadShapeCreation : public logic_error {</p><p>  public:</p><p>    BadShapeCreation(string type)</p><p>      : logic_error("Cannot create type " + type)</p><p>    {}</p><p>  };</p><p>  static Shape* factory(const string&amp; type)</p><p>    throw(BadShapeCreation);</p><p>};</p><empty-line/><p>class Circle : public Shape {</p><p>  Circle() {} // Private constructor</p><p>  friend class Shape;</p><p>public:</p><p>  void draw() { cout &lt;&lt; "Circle::draw\n"; }</p><p>  void erase() { cout &lt;&lt; "Circle::erase\n"; }</p><p>  ~Circle() { cout &lt;&lt; "Circle::~Circle\n"; }</p><p>};</p><empty-line/><p>class Square : public Shape {</p><p>  Square() {}</p><p>  friend class Shape;</p><p>public:</p><p>  void draw() { cout &lt;&lt; "Square::draw\n"; }</p><p>  void erase() { cout &lt;&lt; "Square::erase\n"; }</p><p>  ~Square() { cout &lt;&lt; "Square::~Square\n"; }</p><p>};</p><empty-line/><p>Shape* Shape::factory(const string&amp; type)</p><p>  throw(Shape::BadShapeCreation) {</p><p>  if(type == "Circle") return new Circle;</p><p>  if(type == "Square") return new Square;</p><p>  throw BadShapeCreation(type);</p><p>}</p><empty-line/><p>char* shlist[] = { "Circle", "Square", "Square",</p><p>  "Circle", "Circle", "Circle", "Square", "" };</p><empty-line/><p>int main() {</p><p>  vector&lt;Shape*&gt; shapes;</p><p>  try {</p><p>    for(char** cp = shlist; **cp; cp++)</p><p>      shapes.push_back(Shape::factory(*cp));</p><p>  } catch(Shape::BadShapeCreation e) {</p><p>    cout &lt;&lt; e.what() &lt;&lt; endl;</p><p>    purge(shapes);</p><p>    return 1;</p><p>  }</p><p>  for(size_t i = 0; i &lt; shapes.size(); i++) {</p><p>    shapes[i]-&gt;draw();</p><p>    shapes[i]-&gt;erase();</p><p>  }</p><p>  purge(shapes);</p><p>} ///:~</p><empty-line/><p>The <strong>factory( )</strong> function takes an argument that allows it to determine what type of <strong>Shape</strong> to create; it happens to be a <strong>string</strong> in this case, but it could be any set of data. The <strong>factory( )</strong> is now the only other code in the system that needs to be changed when a new type of <strong>Shape </strong>is added. (The initialization data for the objects will presumably come from somewhere outside the system and will not be a hard-coded array as in the previous example.<sup>)</sup></p><p>To ensure that the creation can only happen in the <strong>factory( )</strong>, the constructors for the specific types of <strong>Shape</strong> are made <strong>private</strong>, and <strong>Shape</strong> is declared a <strong>friend</strong> so that <strong>factory( )</strong> has access to the constructors. (You could also declare only <strong>Shape::factory( )</strong> to be a <strong>friend</strong>, but it seems reasonably harmless to declare the entire base class as a <strong>friend.</strong><sup><strong>)</strong></sup></p></section><section><title><p>Polymorphic factories</p></title><p>The <strong>static factory( )</strong> member function in the previous example forces all the creation operations to be focused in one spot, so that’s the only place you need to change the code. This is certainly a reasonable solution, as it nicely encapsulates the process of creating objects. However, <emphasis>Design Patterns</emphasis> emphasizes that the reason for the Factory Method pattern is so that different types of factories can be derived from the basic factory. Factory Method is in fact a special type of polymorphic factory. However, <emphasis>Design Patterns</emphasis> does not provide an example, but instead just repeats the example used for the <emphasis>Abstract Factory</emphasis>. Here is <strong>ShapeFactory1.cpp</strong> modified so the Factory Methods are in a separate class as virtual functions<sup>:</sup></p><p>//: C10:ShapeFactory2.cpp</p><p>// Polymorphic Factory Methods</p><p>#include &lt;iostream&gt;</p><p>#include &lt;map&gt;</p><p>#include &lt;stdexcept&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../purge.h"</p><p>using namespace std;</p><empty-line/><p>class Shape {</p><p>public:</p><p>  virtual void draw() = 0;</p><p>  virtual void erase() = 0;</p><p>  virtual ~Shape() {}</p><p>};</p><empty-line/><p>class ShapeFactory {</p><p>  virtual Shape* create() = 0;</p><p>  static map&lt;string, ShapeFactory*&gt; factories;</p><p>public:</p><p>  virtual ~ShapeFactory() {}</p><p>  friend class ShapeFactoryInitializer;</p><p>  class BadShapeCreation : public logic_error {</p><p>  public:</p><p>    BadShapeCreation(string type)</p><p>      : logic_error("Cannot create type " + type)</p><p>    {}</p><p>  };</p><p>  static Shape*</p><p>  createShape(const string&amp; id) throw(BadShapeCreation){</p><p>    if(factories.find(id) != factories.end())</p><p>      return factories[id]-&gt;create();</p><p>    else</p><p>      throw BadShapeCreation(id);</p><p>  }</p><p>};</p><empty-line/><p>// Define the static object:</p><p>map&lt;string, ShapeFactory*&gt;</p><p>  ShapeFactory::factories;</p><empty-line/><p>class Circle : public Shape {</p><p>  Circle() {} // Private constructor</p><p>public:</p><p>  void draw() { cout &lt;&lt; "Circle::draw\n"; }</p><p>  void erase() { cout &lt;&lt; "Circle::erase\n"; }</p><p>  ~Circle() { cout &lt;&lt; "Circle::~Circle\n"; }</p><p>private:</p><p>  friend class ShapeFactoryInitializer;</p><p>  class Factory;</p><p>  friend class Factory;</p><p>  class Factory : public ShapeFactory {</p><p>  public:</p><p>    Shape* create() { return new Circle; }</p><p>    friend class ShapeFactoryInitializer;</p><p>  };</p><p>};</p><empty-line/><p>class Square : public Shape {</p><p>  Square() {}</p><p>public:</p><p>  void draw() { cout &lt;&lt; "Square::draw\n"; }</p><p>  void erase() { cout &lt;&lt; "Square::erase\n"; }</p><p>  ~Square() { cout &lt;&lt; "Square::~Square\n"; }</p><p>private:</p><p>  friend class ShapeFactoryInitializer;</p><p>  class Factory;</p><p>  friend class Factory;</p><p>  class Factory : public ShapeFactory {</p><p>  public:</p><p>    Shape* create() { return new Square; }</p><p>    friend class ShapeFactoryInitializer;</p><p>  };</p><p>};</p><empty-line/><p>// Singleton to initialize the ShapeFactory:</p><p>class ShapeFactoryInitializer {</p><p>  static ShapeFactoryInitializer si;</p><p>  ShapeFactoryInitializer() {</p><p>    ShapeFactory::factories["Circle"] =</p><p>      new Circle::Factory;</p><p>    ShapeFactory::factories["Square"] =</p><p>      new Square::Factory;</p><p>  }</p><p>  ~ShapeFactoryInitializer() {</p><p>    delete ShapeFactory::factories["Circle"];</p><p>    delete ShapeFactory::factories["Square"];</p><p>  }</p><p>};</p><empty-line/><p>// Static member definition:</p><p>ShapeFactoryInitializer</p><p>  ShapeFactoryInitializer::si;</p><empty-line/><p>char* shlist[] = { "Circle", "Square", "Square",</p><p>  "Circle", "Circle", "Circle", "Square", "" };</p><empty-line/><p>int main() {</p><p>  vector&lt;Shape*&gt; shapes;</p><p>  try {</p><p>    for(char** cp = shlist; **cp; cp++)</p><p>      shapes.push_back(</p><p>        ShapeFactory::createShape(*cp));</p><p>  } catch(ShapeFactory::BadShapeCreation e) {</p><p>    cout &lt;&lt; e.what() &lt;&lt; endl;</p><p>    return 1;</p><p>  }</p><p>  for(size_t i = 0; i &lt; shapes.size(); i++) {</p><p>    shapes[i]-&gt;draw();</p><p>    shapes[i]-&gt;erase();</p><p>  }</p><p>  purge(shapes);</p><p>} ///:~</p><empty-line/><p>Now the Factory Method appears in its own class, <strong>ShapeFactory</strong>, as the <strong>virtual create( )</strong>. This is a private member function, which means it cannot be called directly but can be overridden. The subclasses of <strong>Shape</strong> must each create their own subclasses of <strong>ShapeFactory</strong> and override the <strong>create( )</strong> member function to create an object of their own type. These factories are private, so that they are only accessible from the main Factory Method. This way, all client code must go through the Factory Method in order to create objects<sup>.</sup></p><p>The actual creation of shapes is performed by calling <strong>ShapeFactory::createShape( )</strong>, which is a static member function that uses the <strong>map</strong> in <strong>ShapeFactory</strong> to find the appropriate factory object based on an identifier that you pass it. The factory is immediately used to create the shape object, but you could imagine a more complex problem in which the appropriate factory object is returned and then used by the caller to create an object in a more sophisticated way. However, it seems that much of the time you don’t need the intricacies of the polymorphic Factory Method, and a single static member function in the base class (as shown in <strong>ShapeFactory1.cpp</strong>) will work fine<sup>.</sup></p><p>Notice that the <strong>ShapeFactory</strong> must be initialized by loading its <strong>map</strong> with factory objects, which takes place in the Singleton <strong>ShapeFactoryInitializer</strong>. So to add a new type to this design you must define the type, create a factory, and modify <strong>ShapeFactoryInitializer</strong> so that an instance of your factory is inserted in the map. This extra complexity again suggests the use of a <strong>static</strong> Factory Method if you don’t need to create individual factory objects<sup>.</sup></p></section><section><title><p>Abstract factories</p></title><p>The Abstract Factory pattern looks like the factory objects we’ve seen previously, with not one but several Factory Methods. Each of the Factory Methods creates a different kind of object. The idea is that when you create the factory object, you decide how all the objects created by that factory will be used. The example in <emphasis>Design Patterns</emphasis> implements portability across various graphical user interfaces (GUIs): you create a factory object appropriate to the GUI that you’re working with, and from then on when you ask it for a menu, a button, a slider, and so on, it will automatically create the appropriate version of that item for the GUI. Thus, you’re able to isolate, in one place, the effect of changing from one GUI to another<sup>.</sup></p><p>As another example, suppose you are creating a general-purpose gaming environment and you want to be able to support different types of games. Here’s how it might look using an Abstract Factory<sup>:</sup></p><p>//: C10:AbstractFactory.cpp</p><p>// A gaming environment</p><p>#include &lt;iostream&gt;</p><p>using namespace std;</p><empty-line/><p>class Obstacle {</p><p>public:</p><p>  virtual void action() = 0;</p><p>};</p><empty-line/><p>class Player {</p><p>public:</p><p>  virtual void interactWith(Obstacle*) = 0;</p><p>};</p><empty-line/><p>class Kitty: public Player {</p><p>  virtual void interactWith(Obstacle* ob) {</p><p>    cout &lt;&lt; "Kitty has encountered a ";</p><p>    ob-&gt;action();</p><p>  }</p><p>};</p><empty-line/><p>class KungFuGuy: public Player {</p><p>  virtual void interactWith(Obstacle* ob) {</p><p>    cout &lt;&lt; "KungFuGuy now battles against a ";</p><p>    ob-&gt;action();</p><p>  }</p><p>};</p><empty-line/><p>class Puzzle: public Obstacle {</p><p>public:</p><p>  void action() { cout &lt;&lt; "Puzzle\n"; }</p><p>};</p><empty-line/><p>class NastyWeapon: public Obstacle {</p><p>public:</p><p>  void action() { cout &lt;&lt; "NastyWeapon\n"; }</p><p>};</p><empty-line/><p>// The abstract factory:</p><p>class GameElementFactory {</p><p>public:</p><p>  virtual Player* makePlayer() = 0;</p><p>  virtual Obstacle* makeObstacle() = 0;</p><p>};</p><empty-line/><p>// Concrete factories:</p><p>class KittiesAndPuzzles :</p><p>  public GameElementFactory {</p><p>public:</p><p>  virtual Player* makePlayer() {</p><p>    return new Kitty;</p><p>  }</p><p>  virtual Obstacle* makeObstacle() {</p><p>    return new Puzzle;</p><p>  }</p><p>};</p><empty-line/><p>class KillAndDismember :</p><p>  public GameElementFactory {</p><p>public:</p><p>  virtual Player* makePlayer() {</p><p>    return new KungFuGuy;</p><p>  }</p><p>  virtual Obstacle* makeObstacle() {</p><p>    return new NastyWeapon;</p><p>  }</p><p>};</p><empty-line/><p>class GameEnvironment {</p><p>  GameElementFactory* gef;</p><p>  Player* p;</p><p>  Obstacle* ob;</p><p>public:</p><p>  GameEnvironment(GameElementFactory* factory) :</p><p>    gef(factory), p(factory-&gt;makePlayer()),</p><p>    ob(factory-&gt;makeObstacle()) {}</p><p>  void play() {</p><p>    p-&gt;interactWith(ob);</p><p>  }</p><p>  ~GameEnvironment() {</p><p>    delete p;</p><p>    delete ob;</p><p>    delete gef;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  GameEnvironment</p><p>    g1(new KittiesAndPuzzles),</p><p>    g2(new KillAndDismember);</p><p>  g1.play();</p><p>  g2.play();</p><p>}</p><p>/* Output:</p><p>Kitty has encountered a Puzzle</p><p>KungFuGuy now battles against a NastyWeapon */ ///:~</p><empty-line/><p>In this environment, <strong>Player</strong> objects interact with <strong>Obstacle</strong> objects, but the types of players and obstacles depend on the game. You determine the kind of game by choosing a particular <strong>GameElementFactory</strong>, and then the <strong>GameEnvironment</strong> controls the setup and play of the game. In this example, the setup and play are simple, but those activities (the <emphasis>initial conditions</emphasis> and the <emphasis>state change</emphasis>) can determine much of the game’s outcome. Here, <strong>GameEnvironment</strong> is not designed to be inherited, although it could possibly make sense to do that<sup>.</sup></p><p>This example also illustrates <emphasis>double dispatching</emphasis>, which will be explained later.</p></section><section><title><p>Virtual constructors</p></title><section><p>One of the primary goals of using a factory is to organize your code so you don’t have to select an exact type of constructor when creating an object. That is, you can say, "I don’t know precisely what type of object you are, but here’s the information. Create yourself." </p><p>In addition, during a constructor call the virtual mechanism does not operate (early binding occurs). Sometimes this is awkward. For example, in the <strong>Shape </strong>program it seems logical that inside the constructor for a <strong>Shape</strong> object, you would want to set everything up and then <strong>draw( )</strong> the <strong>Shape</strong>. The <strong>draw( )</strong> function should be a virtual function, a message to the <strong>Shape</strong> that it should draw itself appropriately, depending on whether it is a circle, a square, a line, and so on. However, this doesn’t work inside the constructor, virtual functions resolve to the "local" function bodies when called in constructors<sup>.</sup></p><p>If you want to be able to call a virtual function inside the constructor and have it do the right thing, you must use a technique to <emphasis>simulate</emphasis> a virtual constructor (which is a variation of the Factory Method). This is a conundrum. Remember, the idea of a virtual function is that you send a message to an object and let the object figure out the right thing to do. But a constructor builds an object. So a virtual constructor would be like saying, "I don’t know exactly what type of object you are, but build yourself anyway." In an ordinary constructor, the compiler must know which VTABLE address to bind to the VPTR, and if it existed, a virtual constructor couldn’t do this because it doesn’t know all the type information at compile time. It makes sense that a constructor can’t be virtual because it is the one function that absolutely must know everything about the type of the object</p><p>And yet there are times when you want something approximating the behavior of a virtual constructor.</p><p>In the <strong>Shape</strong> example, it would be nice to hand the <strong>Shape</strong> constructor some specific information in the argument list and let the constructor create a specific type of <strong>Shape</strong> (a <strong>Circle</strong>, <strong>Square</strong>) with no further intervention. Ordinarily, you’d have to make an explicit call to the <strong>Circle</strong>, <strong>Square</strong> constructor yourself<sup>.</sup></p><p>Coplien<a l:href="#n122" type="note">[122]</a> calls his solution to this problem "envelope and letter classes." The "envelope" class is the base class, a shell that contains a pointer to an object of the base class. The constructor for the "envelope" determines (at runtime, when the constructor is called, not at compile time, when the type checking is normally done) what specific type to make, creates an object of that specific type (on the heap), and then assigns the object to its pointer. All the function calls are then handled by the base class through its pointer. So the base class is acting as a proxy for the derived class<sup>:</sup></p><p>//: C10:VirtualConstructor.cpp</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;exception&gt;</p><p>#include &lt;vector&gt;</p><p>using namespace std;</p><empty-line/><p>class Shape {</p><p>  Shape* s;</p><p>  // Prevent copy-construction &amp; operator=</p><p>  Shape(Shape&amp;);</p><p>  Shape operator=(Shape&amp;);</p><p>protected:</p><p>  Shape() { s = 0; };</p><p>public:</p><p>  virtual void draw() { s-&gt;draw(); }</p><p>  virtual void erase() { s-&gt;erase(); }</p><p>  virtual void test() { s-&gt;test(); };</p><p>  virtual ~Shape() {</p><p>    cout &lt;&lt; "~Shape\n";</p><p>    if(s) {</p><p>      cout &lt;&lt; "Making virtual call: ";</p><p>      s-&gt;erase(); // Virtual call</p><p>    }</p><p>    cout &lt;&lt; "delete s: ";</p><p>    delete s; // The polymorphic deletion</p><p>  }</p><p>  class BadShapeCreation : public exception {</p><p>    string reason;</p><p>  public:</p><p>    BadShapeCreation(string type) {</p><p>      reason = "Cannot create type " + type;</p><p>    }</p><p>    ~BadShapeCreation() throw() {}</p><p>    const char *what() const throw() {</p><p>      return reason.c_str();</p><p>    }</p><p>  };</p><p>  Shape(string type) throw(BadShapeCreation);</p><p>};</p><empty-line/><p>class Circle : public Shape {</p><p>  Circle(Circle&amp;);</p><p>  Circle operator=(Circle&amp;);</p><p>  Circle() {} // Private constructor</p><p>  friend class Shape;</p><p>public:</p><p>  void draw() { cout &lt;&lt; "Circle::draw\n"; }</p><p>  void erase() { cout &lt;&lt; "Circle::erase\n"; }</p><p>  void test() { draw(); }</p><p>  ~Circle() { cout &lt;&lt; "Circle::~Circle\n"; }</p><p>};</p><empty-line/><p>class Square : public Shape {</p><p>  Square(Square&amp;);</p><p>  Square operator=(Square&amp;);</p><p>  Square() {}</p><p>  friend class Shape;</p><p>public:</p><p>  void draw() { cout &lt;&lt; "Square::draw\n"; }</p><p>  void erase() { cout &lt;&lt; "Square::erase\n"; }</p><p>  void test() { draw(); }</p><p>  ~Square() { cout &lt;&lt; "Square::~Square\n"; }</p><p>};</p><empty-line/><p>Shape::Shape(string type)</p><p>  throw(Shape::BadShapeCreation) {</p><p>  if(type == "Circle")</p><p>    s = new Circle;</p><p>  else if(type == "Square")</p><p>    s = new Square;</p><p>  else throw BadShapeCreation(type);</p><p>  draw();  // Virtual call in the constructor</p><p>}</p><empty-line/><p>char* shlist[] = { "Circle", "Square", "Square",</p><p>  "Circle", "Circle", "Circle", "Square", "" };</p><empty-line/><p>int main() {</p><p>  vector&lt;Shape*&gt; shapes;</p><p>  cout &lt;&lt; "virtual constructor calls:" &lt;&lt; endl;</p><p>  try {</p><p>    for(char** cp = shlist; **cp; cp++)</p><p>      shapes.push_back(new Shape(*cp));</p><p>  } catch(Shape::BadShapeCreation e) {</p><p>    cout &lt;&lt; e.what() &lt;&lt; endl;</p><p>    for(int j = 0; j &lt; shapes.size(); j++)</p><p>      delete shapes[j];</p><p>    return 1;</p><p>  }</p><p>  for(int i = 0; i &lt; shapes.size(); i++) {</p><p>    shapes[i]-&gt;draw();</p><p>    cout &lt;&lt; "test\n";</p><p>    shapes[i]-&gt;test();</p><p>    cout &lt;&lt; "end test\n";</p><p>    shapes[i]-&gt;erase();</p><p>  }</p><p>  Shape c("Circle"); // Create on the stack</p><p>  cout &lt;&lt; "destructor calls:" &lt;&lt; endl;</p><p>  for(int j = 0; j &lt; shapes.size(); j++) {</p><p>    delete shapes[j];</p><p>    cout &lt;&lt; "\n------------\n";</p><p>  }</p><p>} ///:~</p><empty-line/><p>The base class <strong>Shape</strong> contains a pointer to an object of type <strong>Shape</strong> as its only data member. When you build a "virtual constructor" scheme, exercise special care to ensure this pointer is always initialized to a live object<sup>.</sup></p><p>Each time you derive a new subtype from <strong>Shape</strong>, you must go back and add the creation for that type in one place, inside the "virtual constructor" in the <strong>Shape</strong> base class. This is not too onerous a task, but the disadvantage is you now have a dependency between the <strong>Shape</strong> class and all classes derived from it (a reasonable trade-off, it seems). Also, because it is a proxy, the base-class interface is truly the only thing the user sees<sup>.</sup></p><p>In this example, the information you must hand the virtual constructor about what type to create is explicit: it’s a <strong>string</strong> that names the type. However, your scheme can use other information—for example, in a parser the output of the scanner can be handed to the virtual constructor, which then uses that information to determine which token to create<sup>.</sup></p><p>The virtual constructor <strong>Shape(type)</strong> can only be declared inside the class; it cannot be defined until after all the derived classes have been declared. However, the default constructor can be defined inside <strong>class Shape</strong>, but it should be made <strong>protected</strong> so temporary <strong>Shape</strong> objects cannot be created. This default constructor is only called by the constructors of derived-class objects. You are forced to explicitly create a default constructor because the compiler will create one for you automatically only if there are <emphasis>no</emphasis> constructors defined. Because you must define <strong>Shape(type)</strong>, you must also define <strong>Shape( )</strong><sup><strong>.</strong></sup></p><p>The default constructor in this scheme has at least one important chore—it must set the value of the <strong>s</strong> pointer to zero. This may sound strange at first, but remember that the default constructor will be called as part of the construction of the <emphasis>actual object</emphasis>—in Coplien’s terms, the "letter," not the "envelope." However, the "letter" is derived from the "envelope," so it also inherits the data member <strong>s</strong>. In the "envelope," <strong>s</strong> is important because it points to the actual object, but in the "letter," <strong>s</strong> is simply excess baggage. Even excess baggage should be initialized, however, and if <strong>s</strong> is not set to zero by the default constructor called for the "letter," bad things happen (as you’ll see later)<sup>.</sup></p><p>The virtual constructor takes as its argument information that completely determines the type of the object. Notice, though, that this type information isn’t read and acted upon until runtime, whereas normally the compiler must know the exact type at compile time (one other reason this system effectively imitates virtual constructors)<sup>.</sup></p><p>The virtual constructor uses its argument to select the actual ("letter") object to construct, which is then assigned to the pointer inside the "envelope." At that point, the construction of the "letter" has been completed, so any virtual calls will be properly directed<sup>.</sup></p><p>As an example, consider the call to <strong>draw( )</strong> inside the virtual constructor. If you trace this call (either by hand or with a debugger), you can see that it starts in the <strong>draw( )</strong> function in the base class, <strong>Shape</strong>. This function calls <strong>draw( )</strong> for the "envelope" <strong>s</strong> pointer to its "letter." All types derived from <strong>Shape</strong> share the same interface, so this virtual call is properly executed, even though it seems to be in the constructor. (Actually, the constructor for the "letter" has already completed.) As long as all virtual calls in the base class simply make calls to identical virtual functions through the pointer to the "letter," the system operates properly<sup>.</sup></p><p>To understand how it works, consider the code in <strong>main( )</strong>. To fill the <strong>vector shapes</strong>, "virtual constructor" calls are made to <strong>Shape</strong>. Ordinarily in a situation like this, you would call the constructor for the actual type, and the VPTR for that type would be installed in the object. Here, however, the VPTR used in each case is the one for <strong>Shape</strong>, not the one for the specific <strong>Circle</strong>, <strong>Square</strong>, or <strong>Triangle</strong><sup><strong>.</strong></sup></p><p>In the <strong>for</strong> loop where the <strong>draw( )</strong> and <strong>erase( ) </strong>functions are called for each <strong>Shape</strong>, the virtual function call resolves, through the VPTR, to the corresponding type. However, this is <strong>Shape</strong> in each case. In fact, you might wonder why <strong>draw( )</strong> and <strong>erase( ) </strong>were made <strong>virtual</strong> at all. The reason shows up in the next step: the base-class version of <strong>draw( )</strong> makes a call, through the "letter" pointer <strong>s</strong>, to the <strong>virtual</strong> function <strong>draw( )</strong> for the "letter." This time the call resolves to the actual type of the object, not just the base class <strong>Shape</strong>. Thus, the runtime cost of using virtual constructors is one more virtual call every time you make a virtual function call<sup>.</sup></p><p>To create any function that is overridden, such as <strong>draw( )</strong>, <strong>erase( ),</strong> or <strong>test( )</strong>, you must proxy all calls to the <strong>s</strong> pointer in the base class implementation, as shown earlier. This is because, when the call is made, the call to the envelope’s member function will resolve as being to <strong>Shape</strong>, and not to a derived type of <strong>Shape</strong>. Only when you make the proxy call to <strong>s</strong> will the virtual behavior take place. In <strong>main( )</strong>, you can see that everything works correctly, even when calls are made inside constructors and destructors<sup>.</sup></p></section><section><section><title><p>Destructor operation</p></title><p>The activities of destruction in this scheme are also tricky. To understand, let’s verbally walk through what happens when you call <strong>delete</strong> for a pointer to a <strong>Shape</strong> object—specifically, a <strong>Square</strong>—created on the heap. (This is more complicated than an object created on the stack.) This will be a <strong>delete</strong> through the polymorphic interface, as in the statement <strong>delete shapes[i]</strong> in <strong>main( )</strong><sup><strong>.</strong></sup></p><p>The type of the pointer <strong>shapes[i]</strong> is of the base class <strong>Shape</strong>, so the compiler makes the call through <strong>Shape</strong>. Normally, you might say that it’s a virtual call, so <strong>Square</strong>’s destructor will be called. But with the virtual constructor scheme, the compiler is creating actual <strong>Shape</strong> objects, even though the constructor initializes the letter pointer to a specific type of <strong>Shape</strong>. The virtual mechanism <emphasis>is</emphasis> used, but the VPTR inside the <strong>Shape</strong> object is <strong>Shape</strong>’s VPTR, not <strong>Square</strong>’s. This resolves to <strong>Shape</strong>’s destructor, which calls <strong>delete</strong> for the letter pointer <strong>s</strong>, which actually points to a <strong>Square</strong> object. This is again a virtual call, but this time it resolves to <strong>Square</strong>’s destructor<sup>.</sup></p><p>With a destructor, however, C++ guarantees, via the compiler, that all destructors in the hierarchy are called. <strong>Square</strong>’s destructor is called first, followed by any intermediate destructors, in order, until finally the base-class destructor is called. This base-class destructor has code that says <strong>delete s</strong>. When this destructor was called originally, it was for the "envelope" <strong>s</strong>, but now it’s for the "letter" <strong>s</strong>, which is there because the "letter" was inherited from the "envelope," and not because it contains anything. So <emphasis>this</emphasis> call to <strong>delete</strong> should do nothing<sup>.</sup></p><p>The solution to the problem is to make the "letter" <strong>s</strong> pointer zero. Then when the "letter" base-class destructor is called, you get <strong>delete 0</strong>, which by definition does nothing. Because the default constructor is protected, it will be called <emphasis>only</emphasis> during the construction of a "letter," so that’s the only situation in which <strong>s</strong> is set to zero<sup>.</sup></p><p>Your most common tool for hiding construction will probably be ordinary Factory Methods rather than the more complex approaches. The idea of adding new types with minimal effect on the rest of the system will be further explored later in this chapter<sup>.</sup></p></section></section></section></section><section><title><p>Observer</p></title><section><p>The Observer pattern solves a fairly common problem: what if a group of objects needs to update themselves when some other object changes state? This can be seen in the "model-view" aspect of Smalltalk’s MVC (model-view-controller) or the almost-equivalent "Document-View Architecture." Suppose that you have some data (the "document") and more than one view, say a plot and a textual view. When you change the data, the two views must know to update themselves, and that’s what the observer facilitates<sup>.</sup></p><p>Two types of objects are used to implement the observer pattern in the following code. The <strong>Observable</strong> class keeps track of everybody who wants to be informed when a change happens. The <strong>Observable</strong> class calls the <strong>notifyObservers( )</strong> member function for each observer on the list. The <strong>notifyObservers( )</strong> member function is part of the base class <strong>Observable</strong><sup><strong>.</strong></sup></p><p>There are actually two "things that change" in the observer pattern: the quantity of observing objects and the way an update occurs. That is, the observer pattern allows you to modify both of these without affecting the surrounding code<sup>.</sup></p><p>You can implement the observer pattern in a number of ways, but the code shown here will create a framework from which you can build your own observer code, following the example. First, this interface describes what an observer looks like<sup>:</sup></p><p>//: C10:Observer.h</p><p>// The Observer interface</p><p>#ifndef OBSERVER_H</p><p>#define OBSERVER_H</p><empty-line/><p>class Observable;</p><p>class Argument {};</p><empty-line/><p>class Observer {</p><p>public:</p><p>  // Called by the observed object, whenever</p><p>  // the observed object is changed:</p><p>  virtual void</p><p>  update(Observable* o, Argument * arg) = 0;</p><p>};</p><p>#endif // OBSERVER_H ///:~</p><empty-line/><p>Since <strong>Observer</strong> interacts with <strong>Observable</strong> in this approach, <strong>Observable</strong> must be declared first. In addition, the <strong>Argument</strong> class is empty and only acts as a base class for any type of argument you want to pass during an update. If you want, you can simply pass the extra argument as a <strong>void*</strong>. You’ll have to downcast in either case<sup>.</sup></p><p>The <strong>Observer</strong> type is an "interface" class that only has one member function, <strong>update( )</strong>. This function is called by the object that’s being observed, when that object decides it’s time to update all its observers. The arguments are optional; you could have an <strong>update( )</strong> with no arguments, and that would still fit the observer pattern. However this is more general—it allows the observed object to pass the object that caused the update (since an <strong>Observer </strong>may be registered with more than one observed object) and any extra information if that’s helpful, rather than forcing the <strong>Observer</strong> object to hunt around to see who is updating and to fetch any other information it needs<sup>.</sup></p><p>The "observed object" will be of type <strong>Observable</strong>:</p><p>//: C10:Observable.h</p><p>// The Observable class</p><p>#ifndef OBSERVABLE_H</p><p>#define OBSERVABLE_H</p><p>#include "Observer.h"</p><p>#include &lt;set&gt;</p><empty-line/><p>class Observable {</p><p>  bool changed;</p><p>  std::set&lt;Observer*&gt; observers;</p><p>protected:</p><p>  virtual void setChanged() { changed = true; }</p><p>  virtual void clearChanged(){ changed = false; }</p><p>public:</p><p>  virtual void addObserver(Observer&amp; o) {</p><p>    observers.insert(&amp;o);</p><p>  }</p><p>  virtual void deleteObserver(Observer&amp; o) {</p><p>    observers.erase(&amp;o);</p><p>  }</p><p>  virtual void deleteObservers() {</p><p>    observers.clear();</p><p>  }</p><p>  virtual int countObservers() {</p><p>    return observers.size();</p><p>  }</p><p>  virtual bool hasChanged() { return changed; }</p><p>  // If this object has changed, notify all</p><p>  // of its observers:</p><p>  virtual void notifyObservers(Argument* arg = 0) {</p><p>    if(!hasChanged()) return;</p><p>    clearChanged(); // Not "changed" anymore</p><p>    std::set&lt;Observer*&gt;::iterator it;</p><p>    for(it = observers.begin();</p><p>      it != observers.end(); it++)</p><p>      (*it)-&gt;update(this, arg);</p><p>  }</p><p>};</p><p>#endif // OBSERVABLE_H ///:~</p><empty-line/><p>Again, the design here is more elaborate than is necessary; as long as there’s a way to register an <strong>Observer</strong> with an <strong>Observable</strong> and a way for the <strong>Observable</strong> to update its <strong>Observer</strong>s, the set of member functions doesn’t matter. However, this design is intended to be reusable. (It was lifted from the design used in the Java standard library.)<a l:href="#n123" type="note">[123]</a></p><p>The <strong>Observable</strong> object has a flag to indicate whether it’s been changed. In a simpler design, there would be no flag; if something happened, everyone would be notified. Notice, however, that the control of the flag’s state is <strong>protected</strong> so that only an inheritor can decide what constitutes a change, and not the end user of the resulting derived <strong>Observer</strong> class<sup>.</sup></p><p>The collection of <strong>Observer</strong> objects is kept in a <strong>set&lt;Observer*&gt;</strong> to prevent duplicates; the <strong>set insert( )</strong>, <strong>erase( )</strong>, <strong>clear( ),</strong> and <strong>size( )</strong> functions are exposed to allow <strong>Observer</strong>s to be added and removed at any time, thus providing runtime flexibility<sup>.</sup></p><p>Most of the work is done in <strong>notifyObservers( )</strong>. If the <strong>changed</strong> flag has not been set, this does nothing. Otherwise, it first clears the <strong>changed</strong> flag so that repeated calls to <strong>notifyObservers( )</strong> won’t waste time. This is done before notifying the observers in case the calls to <strong>update( )</strong> do anything that causes a change back to this <strong>Observable</strong> object. It then moves through the <strong>set</strong> and calls back to the <strong>update( )</strong> member function of each <strong>Observer</strong><sup><strong>.</strong></sup></p><p>At first it may appear that you can use an ordinary <strong>Observable</strong> object to manage the updates. But this doesn’t work; to get an effect, you <emphasis>must</emphasis> derive from <strong>Observable</strong> and somewhere in your derived-class code call <strong>setChanged( )</strong>. This is the member function that sets the "changed" flag, which means that when you call <strong>notifyObservers( )</strong> all the observers will, in fact, get notified. <emphasis>Where</emphasis> you call <strong>setChanged( )</strong> depends on the logic of your program<sup>.</sup></p><p>Now we encounter a dilemma. Objects that are being observed may have more than one such item of interest. For example, if you’re dealing with a GUI item—a button, say—the items of interest might be the mouse clicked the button, the mouse moved over the button, and (for some reason) the button changed its color. So we’d like to be able to report all these events to different observers, each of which is interested in a different type of event<sup>.</sup></p><p>The problem is that we would normally reach for multiple inheritance in such a situation: "I’ll inherit from <strong>Observable</strong> to deal with mouse clicks, and I’ll … er … inherit from <strong>Observable</strong> to deal with mouse-overs, and, well, … hmm, that doesn’t work." </p></section><section><title><p>The "inner class" idiom</p></title><p>Here’s a situation in which we do actually need to (in effect) upcast to more than one type, but in this case we need to provide several <emphasis>different</emphasis> implementations of the same base type. The solution is something we’ve lifted from Java, which takes C++’s nested class one step further. Java has a built-in feature called an <emphasis>inner class</emphasis>, which is like a nested class in C++, but it has access to the nonstatic data of its containing class by implicitly using the "this" pointer of the class object it was created within.<a l:href="#n124" type="note">[124]</a></p><p>To implement the inner class idiom in C++, we must obtain and use a pointer to the containing object explicitly. Here’s an example:</p><p>//: C10:InnerClassIdiom.cpp</p><p>// Example of the "inner class" idiom</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace std;</p><empty-line/><p>class Poingable {</p><p>public:</p><p>  virtual void poing() = 0;</p><p>};</p><empty-line/><p>void callPoing(Poingable&amp; p) {</p><p>  p.poing();</p><p>}</p><empty-line/><p>class Bingable {</p><p>public:</p><p>  virtual void bing() = 0;</p><p>};</p><empty-line/><p>void callBing(Bingable&amp; b) {</p><p>  b.bing();</p><p>}</p><empty-line/><p>class Outer {</p><p>  string name;</p><p>  // Define one inner class:</p><p>  class Inner1;</p><p>  friend class Outer::Inner1;</p><p>  class Inner1 : public Poingable {</p><p>    Outer* parent;</p><p>  public:</p><p>    Inner1(Outer* p) : parent(p) {}</p><p>    void poing() {</p><p>      cout &lt;&lt; "poing called for "</p><p>        &lt;&lt; parent-&gt;name &lt;&lt; endl;</p><p>      // Accesses data in the outer class object</p><p>    }</p><p>  } inner1;</p><p>  // Define a second inner class:</p><p>  class Inner2;</p><p>  friend class Outer::Inner2;</p><p>  class Inner2 : public Bingable {</p><p>    Outer* parent;</p><p>  public:</p><p>    Inner2(Outer* p) : parent(p) {}</p><p>    void bing() {</p><p>      cout &lt;&lt; "bing called for "</p><p>        &lt;&lt; parent-&gt;name &lt;&lt; endl;</p><p>    }</p><p>  } inner2;</p><p>public:</p><p>  Outer(const string&amp; nm) : name(nm),</p><p>    inner1(this), inner2(this) {}</p><p>  // Return reference to interfaces</p><p>  //  implemented by the inner classes:</p><p>  operator Poingable&amp;() { return inner1; }</p><p>  operator Bingable&amp;() { return inner2; }</p><p>};</p><empty-line/><p>int main() {</p><p>  Outer x("Ping Pong");</p><p>  // Like upcasting to multiple base types!:</p><p>  callPoing(x);</p><p>  callBing(x);</p><p>} ///:~</p><empty-line/><p>The example begins with the <strong>Poingable</strong> and <strong>Bingable </strong>interfaces, each of which contain a single member function. The services provided by <strong>callPoing( )</strong> and <strong>callBing( ) </strong>require that the object they receive implement the <strong>Poingable</strong> and <strong>Bingable </strong>interfaces, respectively, but they put no other requirements on that object so as to maximize the flexibility of using <strong>callPoing( )</strong> and <strong>callBing( )</strong>. Note the lack of <strong>virtual</strong> destructors in either interface—the intent is that you never perform object destruction via the interface<sup>.</sup></p><p>The <strong>Outer</strong> constructor contains some private data (<strong>name</strong>), and it wants to provide both a <strong>Poingable</strong> interface and a <strong>Bingable </strong>interface so it can be used with <strong>callPoing( ) </strong>and <strong>callBing( )</strong>. Of course, in this situation we <emphasis>could</emphasis> simply use multiple inheritance. This example is just intended to show the simplest syntax for the idiom; you’ll see a real use shortly. To provide a <strong>Poingable</strong> object without deriving <strong>Outer</strong> from <strong>Poingable</strong>, the inner class idiom is used. First, the declaration <strong>class Inner</strong> says that, somewhere, there is a nested class of this name. This allows the <strong>friend</strong> declaration for the class, which follows. Finally, now that the nested class has been granted access to all the private elements of <strong>Outer</strong>, the class can be defined. Notice that it keeps a pointer to the <strong>Outer</strong> which created it, and this pointer must be initialized in the constructor. Finally, the <strong>poing( )</strong> function from <strong>Poingable</strong> is implemented. The same process occurs for the second inner class which implements <strong>Bingable</strong>. Each inner class has a single <strong>private</strong> instance created, which is initialized in the <strong>Outer</strong> constructor. By creating the member objects and returning references to them, issues of object lifetime are eliminated<sup>.</sup></p><p>Notice that both inner class definitions are <strong>private</strong>, and in fact the client code doesn’t have any access to details of the implementation, since the two access functions <strong>operator Poingable&amp;( )</strong> and <strong>operator Bingable&amp;( )</strong> only return a reference to the upcast interface, not to the object that implements it. In fact, since the two inner classes are <strong>private</strong>, the client code cannot even downcast to the implementation classes, thus providing complete isolation between interface and implementation<sup>.</sup></p><p>Just to push a point, we’ve taken the extra liberty here of defining the automatic type conversion operators <strong>operator Poingable&amp;( )</strong> and <strong>operator Bingable&amp;( )</strong>. In <strong>main( )</strong>, you can see that these actually allow a syntax that looks like <strong>Outer</strong> multiply inherits from <strong>Poingable</strong> and <strong>Bingable</strong>. The difference is that the casts in this case are one way. You can get the effect of an upcast to <strong>Poingable</strong> or <strong>Bingable</strong>, but you cannot downcast back to an <strong>Outer</strong>. In the following example of <strong>observer</strong>, you’ll see the more typical approach: you provide access to the inner class objects using ordinary member functions, not automatic type conversion operations<sup>.</sup></p></section><section><title><p>The observer example</p></title><p>Armed with the <strong>Observer</strong> and <strong>Observable </strong>header files and the inner class idiom, we can look at an example of the Observer pattern:</p><p>//: C10:ObservedFlower.cpp</p><p>// Demonstration of "observer" pattern</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "Observable.h"</p><p>using namespace std;</p><empty-line/><p>class Flower {</p><p>  bool isOpen;</p><p>public:</p><p>  Flower() : isOpen(false),</p><p>    openNotifier(this), closeNotifier(this) {}</p><p>  void open() { // Opens its petals</p><p>    isOpen = true;</p><p>    openNotifier.notifyObservers();</p><p>    closeNotifier.open();</p><p>  }</p><p>  void close() { // Closes its petals</p><p>    isOpen = false;</p><p>    closeNotifier.notifyObservers();</p><p>    openNotifier.close();</p><p>  }</p><p>  // Using the "inner class" idiom:</p><p>  class OpenNotifier;</p><p>  friend class Flower::OpenNotifier;</p><p>  class OpenNotifier : public Observable {</p><p>    Flower* parent;</p><p>    bool alreadyOpen;</p><p>  public:</p><p>    OpenNotifier(Flower* f) : parent(f),</p><p>      alreadyOpen(false) {}</p><p>    void notifyObservers(Argument* arg = 0) {</p><p>      if(parent-&gt;isOpen &amp;&amp; !alreadyOpen) {</p><p>        setChanged();</p><p>        Observable::notifyObservers();</p><p>        alreadyOpen = true;</p><p>      }</p><p>    }</p><p>    void close() { alreadyOpen = false; }</p><p>  } openNotifier;</p><p>  class CloseNotifier;</p><p>  friend class Flower::CloseNotifier;</p><p>  class CloseNotifier : public Observable {</p><p>    Flower* parent;</p><p>    bool alreadyClosed;</p><p>  public:</p><p>    CloseNotifier(Flower* f) : parent(f),</p><p>      alreadyClosed(false) {}</p><p>    void notifyObservers(Argument* arg = 0) {</p><p>      if(!parent-&gt;isOpen &amp;&amp; !alreadyClosed) {</p><p>        setChanged();</p><p>        Observable::notifyObservers();</p><p>        alreadyClosed = true;</p><p>      }</p><p>    }</p><p>    void open() { alreadyClosed = false; }</p><p>  } closeNotifier;</p><p>};</p><empty-line/><p>class Bee {</p><p>  string name;</p><p>  // An "inner class" for observing openings:</p><p>  class OpenObserver;</p><p>  friend class Bee::OpenObserver;</p><p>  class OpenObserver : public Observer {</p><p>    Bee* parent;</p><p>  public:</p><p>    OpenObserver(Bee* b) : parent(b) {}</p><p>    void update(Observable*, Argument *) {</p><p>      cout &lt;&lt; "Bee " &lt;&lt; parent-&gt;name</p><p>        &lt;&lt; "'s breakfast time!\n";</p><p>    }</p><p>  } openObsrv;</p><p>  // Another "inner class" for closings:</p><p>  class CloseObserver;</p><p>  friend class Bee::CloseObserver;</p><p>  class CloseObserver : public Observer {</p><p>    Bee* parent;</p><p>  public:</p><p>    CloseObserver(Bee* b) : parent(b) {}</p><p>    void update(Observable*, Argument *) {</p><p>      cout &lt;&lt; "Bee " &lt;&lt; parent-&gt;name</p><p>        &lt;&lt; "'s bed time!\n";</p><p>    }</p><p>  } closeObsrv;</p><p>public:</p><p>  Bee(string nm) : name(nm),</p><p>    openObsrv(this), closeObsrv(this) {}</p><p>  Observer&amp; openObserver() { return openObsrv; }</p><p>  Observer&amp; closeObserver() { return closeObsrv;}</p><p>};</p><empty-line/><p>class Hummingbird {</p><p>  string name;</p><p>  class OpenObserver;</p><p>  friend class Hummingbird::OpenObserver;</p><p>  class OpenObserver : public Observer {</p><p>    Hummingbird* parent;</p><p>  public:</p><p>    OpenObserver(Hummingbird* h) : parent(h) {}</p><p>    void update(Observable*, Argument *) {</p><p>      cout &lt;&lt; "Hummingbird " &lt;&lt; parent-&gt;name</p><p>        &lt;&lt; "'s breakfast time!\n";</p><p>    }</p><p>  } openObsrv;</p><p>  class CloseObserver;</p><p>  friend class Hummingbird::CloseObserver;</p><p>  class CloseObserver : public Observer {</p><p>    Hummingbird* parent;</p><p>  public:</p><p>    CloseObserver(Hummingbird* h) : parent(h) {}</p><p>    void update(Observable*, Argument *) {</p><p>      cout &lt;&lt; "Hummingbird " &lt;&lt; parent-&gt;name</p><p>        &lt;&lt; "'s bed time!\n";</p><p>    }</p><p>  } closeObsrv;</p><p>public:</p><p>  Hummingbird(string nm) : name(nm),</p><p>    openObsrv(this), closeObsrv(this) {}</p><p>  Observer&amp; openObserver() { return openObsrv; }</p><p>  Observer&amp; closeObserver() { return closeObsrv;}</p><p>};</p><empty-line/><p>int main() {</p><p>  Flower f;</p><p>  Bee ba("A"), bb("B");</p><p>  Hummingbird ha("A"), hb("B");</p><p>  f.openNotifier.addObserver(ha.openObserver());</p><p>  f.openNotifier.addObserver(hb.openObserver());</p><p>  f.openNotifier.addObserver(ba.openObserver());</p><p>  f.openNotifier.addObserver(bb.openObserver());</p><p>  f.closeNotifier.addObserver(ha.closeObserver());</p><p>  f.closeNotifier.addObserver(hb.closeObserver());</p><p>  f.closeNotifier.addObserver(ba.closeObserver());</p><p>  f.closeNotifier.addObserver(bb.closeObserver());</p><p>  // Hummingbird B decides to sleep in:</p><p>  f.openNotifier.deleteObserver(hb.openObserver());</p><p>  // Something changes that interests observers:</p><p>  f.open();</p><p>  f.open(); // It's already open, no change.</p><p>  // Bee A doesn't want to go to bed:</p><p>  f.closeNotifier.deleteObserver(</p><p>    ba.closeObserver());</p><p>  f.close();</p><p>  f.close(); // It's already closed; no change</p><p>  f.openNotifier.deleteObservers();</p><p>  f.open();</p><p>  f.close();</p><p>} ///:~</p><empty-line/><p>The events of interest are that a <strong>Flower</strong> can open or close. Because of the use of the inner class idiom, both these events can be separately observable phenomena. The <strong>OpenNotifier</strong> and <strong>CloseNotifier</strong> classes both derive from <strong>Observable</strong>, so they have access to <strong>setChanged( )</strong> and can be handed to anything that needs an <strong>Observable</strong>. You’ll notice that, contrary to <strong>InnerClassIdiom.cpp</strong>, the <strong>Observable</strong> descendants are <strong>public</strong>. This is because some of their member functions must be available to the client programmer. There’s nothing that says that an inner class must be <strong>private</strong>; in <strong>InnerClassIdiom.cpp</strong> we were simply following the design guideline "make things as private as possible." You could make the classes <strong>private</strong> and expose the appropriate member functions by proxy in <strong>Flower</strong>, but it wouldn’t gain much<sup>.</sup></p><p>The inner class idiom also comes in handy to define more than one kind of <strong>Observer</strong>, in <strong>Bee</strong> and <strong>Hummingbird</strong>, since both those classes may want to independently observe <strong>Flower</strong> openings and closings. Notice how the inner class idiom provides something that has most of the benefits of inheritance (the ability to access the private data in the outer class, for example)<sup>.</sup></p><p>In <strong>main( )</strong>, you can see one of the primary benefits of the Observer pattern: the ability to change behavior at runtime by dynamically registering and unregistering <strong>Observer</strong>s with <strong>Observable</strong>s<sup>.</sup></p><p>If you study the previous code, you’ll see that <strong>OpenNotifier </strong>and <strong>CloseNotifier</strong> use the basic <strong>Observable</strong> interface. This means that you could derive from other completely different <strong>Observer</strong> classes; the only connection the <strong>Observer</strong>s have with <strong>Flower</strong>s is the <strong>Observer</strong> interface<sup>.</sup></p></section></section><section><title><p>Multiple dispatching</p></title><section><p>When dealing with multiple types that are interacting, a program can get particularly messy. For example, consider a system that parses and executes mathematical expressions. You want to be able to say <strong>Number + Number</strong>, <strong>Number * Number</strong>, and so on, where <strong>Number</strong> is the base class for a family of numerical objects. But when you say <strong>a + b</strong>, and you don’t know the exact type of either <strong>a</strong> or <strong>b</strong>, how can you get them to interact properly? </p><p>The answer starts with something you probably don’t think about: C++ performs only single dispatching. That is, if you are performing an operation on more than one object whose type is unknown, C++ can invoke the dynamic binding mechanism on only one of those types. This doesn’t solve the problem, so you end up detecting some types manually and effectively producing your own dynamic binding behavior<sup>.</sup></p><p>The solution is called <emphasis>multiple dispatching</emphasis>. Remember that polymorphism can occur only via member function calls, so if you want double dispatching to occur, there must be two member function calls: the first to determine the first unknown type, and the second to determine the second unknown type. With multiple dispatching, you must have a virtual call for each of the types. Generally, you’ll set up a configuration such that a single member function call produces more than one dynamic member function call and thus services more than one type in the process. To get this effect, you need to work with more than one virtual function: you’ll need a virtual function call for each dispatch. The virtual functions in the following example are called <strong>compete( ) </strong>and <strong>eval( )</strong> and are both members of the same type. (In this case, there will be only two dispatches, which is referred to as <emphasis>double dispatching.</emphasis>) If you are working with two different type hierarchies that are interacting, you’ll need a virtual call in each hierarchy<sup>.</sup></p><p>Here’s an example of multiple dispatching:</p><p>//: C10:PaperScissorsRock.cpp</p><p>// Demonstration of multiple dispatching</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;iterator&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../purge.h"</p><p>using namespace std;</p><empty-line/><p>class Paper;</p><p>class Scissors;</p><p>class Rock;</p><empty-line/><p>enum Outcome { win, lose, draw };</p><empty-line/><p>ostream&amp;</p><p>operator&lt;&lt;(ostream&amp; os, const Outcome out) {</p><p>  switch(out) {</p><p>    default:</p><p>    case win: return os &lt;&lt; "win";</p><p>    case lose: return os &lt;&lt; "lose";</p><p>    case draw: return os &lt;&lt; "draw";</p><p>  }</p><p>}</p><empty-line/><p>class Item {</p><p>public:</p><p>  virtual Outcome compete(const Item*) = 0;</p><p>  virtual Outcome eval(const Paper*) const = 0;</p><p>  virtual Outcome eval(const Scissors*) const= 0;</p><p>  virtual Outcome eval(const Rock*) const = 0;</p><p>  virtual ostream&amp; print(ostream&amp; os) const = 0;</p><p>  virtual ~Item() {}</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Item* it) {</p><p>    return it-&gt;print(os);</p><p>  }</p><p>};</p><empty-line/><p>class Paper : public Item {</p><p>public:</p><p>  Outcome compete(const Item* it) {</p><p>    return it-&gt;eval(this);</p><p>  }</p><p>  Outcome eval(const Paper*) const {</p><p>    return draw;</p><p>  }</p><p>  Outcome eval(const Scissors*) const {</p><p>    return win;</p><p>  }</p><p>  Outcome eval(const Rock*) const {</p><p>    return lose;</p><p>  }</p><p>  ostream&amp; print(ostream&amp; os) const {</p><p>    return os &lt;&lt; "Paper   ";</p><p>  }</p><p>};</p><empty-line/><p>class Scissors : public Item {</p><p>public:</p><p>  Outcome compete(const Item* it) {</p><p>    return it-&gt;eval(this);</p><p>  }</p><p>  Outcome eval(const Paper*) const {</p><p>    return lose;</p><p>  }</p><p>  Outcome eval(const Scissors*) const {</p><p>    return draw;</p><p>  }</p><p>  Outcome eval(const Rock*) const {</p><p>    return win;</p><p>  }</p><p>  ostream&amp; print(ostream&amp; os) const {</p><p>    return os &lt;&lt; "Scissors";</p><p>  }</p><p>};</p><empty-line/><p>class Rock : public Item {</p><p>public:</p><p>  Outcome compete(const Item* it) {</p><p>    return it-&gt;eval(this);</p><p>  }</p><p>  Outcome eval(const Paper*) const {</p><p>    return win;</p><p>  }</p><p>  Outcome eval(const Scissors*) const {</p><p>    return lose;</p><p>  }</p><p>  Outcome eval(const Rock*) const {</p><p>    return draw;</p><p>  }</p><p>  ostream&amp; print(ostream&amp; os) const {</p><p>    return os &lt;&lt; "Rock    ";</p><p>  }</p><p>};</p><empty-line/><p>struct ItemGen {</p><p>  ItemGen() { srand(time(0)); }</p><p>  Item* operator()() {</p><p>    switch(rand() % 3) {</p><p>      default:</p><p>      case 0:</p><p>        return new Scissors;</p><p>      case 1:</p><p>        return new Paper;</p><p>      case 2:</p><p>        return new Rock;</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>struct Compete {</p><p>  Outcome operator()(Item* a, Item* b) {</p><p>    cout &lt;&lt; a &lt;&lt; "\t" &lt;&lt; b &lt;&lt; "\t";</p><p>    return a-&gt;compete(b);</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  const int sz = 20;</p><p>  vector&lt;Item*&gt; v(sz*2);</p><p>  generate(v.begin(), v.end(), ItemGen());</p><p>  transform(v.begin(), v.begin() + sz,</p><p>    v.begin() + sz,</p><p>    ostream_iterator&lt;Outcome&gt;(cout, "\n"),</p><p>    Compete());</p><p>  purge(v);</p><p>} ///:~</p><empty-line/></section><section><title><p>Multiple dispatching with Visitor</p></title><p>The assumption is that you have a primary class hierarchy that is fixed; perhaps it’s from another vendor and you can’t make changes to that hierarchy. However, you’d like to add new polymorphic member functions to that hierarchy, which means that normally you’d have to add something to the base class interface. So the dilemma is that you need to add member functions to the base class, but you can’t touch the base class. How do you get around this? </p><p>The design pattern that solves this kind of problem is called a "visitor" (the final one in <emphasis>Design Patterns</emphasis>), and it builds on the double<emphasis>-</emphasis>dispatching scheme shown in the previous section<sup>.</sup></p><p>The Visitor pattern allows you to extend the interface of the primary type by creating a separate class hierarchy of type <strong>Visitor </strong>to "virtualize" the operations performed on the primary type. The objects of the primary type simply "accept" the visitor and then call the visitor’s dynamically<strong>-</strong>bound member function<sup>.</sup></p><p>//: C10:BeeAndFlowers.cpp</p><p>// Demonstration of "visitor" pattern</p><p>#include &lt;algorithm&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;vector&gt;</p><p>#include "../purge.h"</p><p>using namespace std;</p><empty-line/><p>class Gladiolus;</p><p>class Renuculus;</p><p>class Chrysanthemum;</p><empty-line/><p>class Visitor {</p><p>public:</p><p>  virtual void visit(Gladiolus* f) = 0;</p><p>  virtual void visit(Renuculus* f) = 0;</p><p>  virtual void visit(Chrysanthemum* f) = 0;</p><p>  virtual ~Visitor() {}</p><p>};</p><empty-line/><p>class Flower {</p><p>public:</p><p>  virtual void accept(Visitor&amp;) = 0;</p><p>  virtual ~Flower() {}</p><p>};</p><empty-line/><p>class Gladiolus : public Flower {</p><p>public:</p><p>  virtual void accept(Visitor&amp; v) {</p><p>    v.visit(this);</p><p>  }</p><p>};</p><empty-line/><p>class Renuculus : public Flower {</p><p>public:</p><p>  virtual void accept(Visitor&amp; v) {</p><p>    v.visit(this);</p><p>  }</p><p>};</p><empty-line/><p>class Chrysanthemum : public Flower {</p><p>public:</p><p>  virtual void accept(Visitor&amp; v) {</p><p>    v.visit(this);</p><p>  }</p><p>};</p><empty-line/><p>// Add the ability to produce a string:</p><p>class StringVal : public Visitor {</p><p>  string s;</p><p>public:</p><p>  operator const string&amp;() { return s; }</p><p>  virtual void visit(Gladiolus*) {</p><p>    s = "Gladiolus";</p><p>  }</p><p>  virtual void visit(Renuculus*) {</p><p>    s = "Renuculus";</p><p>  }</p><p>  virtual void visit(Chrysanthemum*) {</p><p>    s = "Chrysanthemum";</p><p>  }</p><p>};</p><empty-line/><p>// Add the ability to do "Bee" activities:</p><p>class Bee : public Visitor {</p><p>public:</p><p>  virtual void visit(Gladiolus*) {</p><p>    cout &lt;&lt; "Bee and Gladiolus\n";</p><p>  }</p><p>  virtual void visit(Renuculus*) {</p><p>    cout &lt;&lt; "Bee and Renuculus\n";</p><p>  }</p><p>  virtual void visit(Chrysanthemum*) {</p><p>    cout &lt;&lt; "Bee and Chrysanthemum\n";</p><p>  }</p><p>};</p><empty-line/><p>struct FlowerGen {</p><p>  FlowerGen() { srand(time(0)); }</p><p>  Flower* operator()() {</p><p>    switch(rand() % 3) {</p><p>      default:</p><p>      case 0: return new Gladiolus;</p><p>      case 1: return new Renuculus;</p><p>      case 2: return new Chrysanthemum;</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  vector&lt;Flower*&gt; v(10);</p><p>  generate(v.begin(), v.end(), FlowerGen());</p><p>  vector&lt;Flower*&gt;::iterator it;</p><p>  // It's almost as if I added a virtual function</p><p>  // to produce a Flower string representation:</p><p>  StringVal sval;</p><p>  for(it = v.begin(); it != v.end(); it++) {</p><p>    (*it)-&gt;accept(sval);</p><p>    cout &lt;&lt; string(sval) &lt;&lt; endl;</p><p>  }</p><p>  // Perform "Bee" operation on all Flowers:</p><p>  Bee bee;</p><p>  for(it = v.begin(); it != v.end(); it++)</p><p>    (*it)-&gt;accept(bee);</p><p>  purge(v);</p><p>} ///:~</p><empty-line/></section></section><section><title><p>Exercises</p></title><p>1.Starting with <strong>SingletonPattern.cpp</strong>, create a class that provides a connection to a service that stores and retrieves data from a configuration file.</p><p>2.Using <strong>SingletonPattern.cpp</strong> as a starting point, create a class that manages a fixed number of its own objects. Assume the objects are database connections and you only have a license to use a fixed quantity of these at any one time.</p><p>3.Create a minimal Observer-Observable design in two classes, without base classes and without the extra arguments in <strong>Observer.h</strong> and the member functions in <strong>Observable.h</strong>. Just create the bare minimum in the two classes, and then demonstrate your design by creating one <strong>Observable</strong> and many <strong>Observer</strong>s and cause the <strong>Observable</strong> to update the <strong>Observer</strong>s.</p><p><strong>4.              </strong>Change <strong>InnerClassIdiom.cpp</strong> so that <strong>Outer</strong> uses multiple inheritance instead of the inner class idiom.</p><p>5.Explain how <strong>AbstractFactory.cpp</strong> demonstrates <emphasis>Double Dispatching</emphasis> and the <emphasis>Factory Method</emphasis>.</p><p>6.Modify <strong>ShapeFactory2.cpp</strong> so that it uses an <emphasis>Abstract Factory</emphasis> to create different sets of shapes (for example, one particular type of factory object creates "thick shapes," another creates "thin shapes," but each factory object can create all the shapes: circles, squares, triangles, and so on).</p><p>7.Create a business-modeling environment with three types of <strong>Inhabitant</strong>: <strong>Dwarf</strong> (for engineers), <strong>Elf</strong> (for marketers), and <strong>Troll</strong> (for managers). Now create a class called <strong>Project</strong> that creates the different inhabitants and causes them to <strong>interact( )</strong> with each other using multiple dispatching.</p><p>8.Modify the example in exercise 7 to make the interactions more detailed. Each <strong>Inhabitant</strong> can randomly produce a <strong>Weapon</strong> using <strong>getWeapon( )</strong>: a <strong>Dwarf</strong> uses <strong>Jargon</strong> or <strong>Play</strong>, an <strong>Elf</strong> uses <strong>InventFeature</strong> or <strong>SellImaginaryProduct</strong>, and a <strong>Troll</strong> uses <strong>Edict</strong> and <strong>Schedule</strong>. You decide which weapons "win" and "lose" in each interaction (as in <strong>PaperScissorsRock.cpp</strong>). Add a <strong>battle( )</strong> member function to <strong>Project</strong> that takes two <strong>Inhabitant</strong>s and matches them against each other. Now create a <strong>meeting( )</strong> member function for <strong>Project</strong> that creates groups of <strong>Dwarf</strong>, <strong>Elf,</strong> and <strong>Manager</strong> and battles the groups against each other until only members of one group are left standing. These are the "winners."</p></section></section><section><title><p>11: Concurrency</p></title><section><p>Objects provide a way to divide a program into independent sections. Often, you also need to partition a program into separate, independently running subtasks.</p><p>Using <emphasis>multithreading</emphasis>, each of these independent subtasks is driven by a <emphasis>thread of execution</emphasis>, and you program as if each thread runs by itself and has the CPU to itself. An underlying mechanism is actually dividing up the CPU time for you, but in general, you don’t have to think about it, which helps to simplify programming with multiple threads.</p><p>A <emphasis>process</emphasis> is a self-contained program running with its own address space. A <emphasis>multitasking</emphasis> operating system can run more than one process (program) at a time, while making it look as if each one is chugging along on its own, by periodically switching the CPU from one task to another. A <emphasis>thread</emphasis> is a single sequential flow of control <emphasis>within</emphasis> a process. A single process can thus have multiple concurrently executing threads.</p><p>There are many possible uses for multithreading, but you’ll most often want to use it when you have some part of your program tied to a particular event or resource. To keep from holding up the rest of your program, you create a thread associated with that event or resource and let it run independently of the main program.</p><p>Concurrent programming is like stepping into an entirely new world and learning a new programming language, or at least a new set of language concepts. With the appearance of thread support in most microcomputer operating systems, extensions for threads have also been appearing in programming languages or libraries. In all cases, thread programming:</p><p>1.       Seems mysterious and requires a shift in the way you think about programming.</p><p>2.      Looks similar to thread support in other languages. When you understand threads, you understand a common tongue.</p><p>Understanding concurrent programming is on the same order of difficulty as understanding polymorphism. If you apply some effort, you can fathom the basic mechanism, but it generally takes deep study and understanding to develop a true grasp of the subject. The goal of this chapter is to give you a solid foundation in the basics of concurrency so that you can understand the concepts and write reasonable multithreaded programs. Be aware that you can easily become overconfident. If you are writing anything complex, you will need to study dedicated books on the topic.</p></section><section><title><p>Motivation</p></title><p>One of the most compelling reasons for using concurrency is to produce a responsive user interface. Consider a program that performs some CPU-intensive operation and thus ends up ignoring user input and being unresponsive. The program needs to continue performing its operations, and at the same time it needs to return control to the user interface so that the program can respond to the user. If you have a "quit" button, you don’t want to be forced to poll it in every piece of code you write in your program. (This would couple your quit button across the program and be a maintenance headache.) Yet you want the quit button to be responsive, as if you <emphasis>were</emphasis> checking it regularly.</p><p>A conventional function cannot continue performing its operations and at the same time return control to the rest of the program. In fact, this sounds like an impossibility, as if the CPU must be in two places at once, but this is precisely the illusion that concurrency provides.</p><p>You can also use concurrency to optimize throughput. For example, you might be able to do important work while you’re stuck waiting for input to arrive on an I/O port. Without threading, the only reasonable solution is to poll the I/O port, which is awkward and can be difficult.</p><p>If you have a multiprocessor machine, multiple threads can be distributed across multiple processors, which can dramatically improve throughput. This is often the case with powerful multiprocessor web servers, which can distribute large numbers of user requests across CPUs in a program that allocates one thread per request.</p><p>One thing to keep in mind is that a program that has many threads must be able to run on a single-CPU machine. Therefore, it must also be possible to write the same program without using any threads. However, multithreading provides an important organizational benefit: The design of your program can be greatly simplified. Some types of problems, such as simulation—a video game, for example—are difficult to solve without support for concurrency.</p><p>The threading model is a programming convenience to simplify juggling several operations at the same time within a single program: The CPU will pop around and give each thread some of its time. Each thread has the consciousness of constantly having the CPU to itself, but the CPU’s time is actually sliced among all the threads. The exception is a program that is running on multiple CPU. But one of the great things about threading is that you are abstracted away from this layer, so your code does not need to know whether it is actually running on a single CPU or many. Thus, using threads is a way to create transparently scalable programs—if a program is running too slowly, you can easily speed it up by adding CPUs to your computer. Multitasking and multithreading tend to be the most reasonable ways to utilize multiprocessor systems.</p><p>Threading can reduce computing efficiency somewhat in single-CPU machines, but the net improvement in program design, resource balancing, and user convenience is often quite valuable. In general, threads enable you to create a more loosely coupled design; otherwise, parts of your code would be forced to pay explicit attention to tasks that would normally be handled by threads.</p></section><section><title><p>Concurrency in C++</p></title><section><p>When the C++ standards committee was creating the initial C++ standard, a concurrency mechanism was explicitly excluded, because C didn’t have one and also because there were a number of competing approaches to implementing concurrency. It seemed too much of a constraint to force programmers to use only one of these.</p><p>The alternative turned out to be worse, however. To use concurrency, you had to find and learn a library and deal with its idiosyncrasies and the uncertainties of working with a particular vendor. In addition, there was no guarantee that such a library would work on different compilers or across different platforms. Also, since concurrency was not part of the standard language, it was more difficult to find C++ programmers that also understood concurrent programming.</p><p>Another influence may have been the Java language, which included concurrency in the core language. Although multithreading is still complicated, Java programmers tend to start learning and using it from the beginning.</p><p>The C++ standards committee is seriously considering the addition of concurrency support to the next iteration of C++, but at the time of this writing it is unclear what the library will look like. Therefore, we decided to use the ZThread library as the basis for this chapter. We preferred the design, and it is open-source and freely available at <emphasis>http://zthread.sourceforge.net</emphasis>. Eric Crahen of IBM, the author of the ZThread library, was instrumental in creating this chapter.<a l:href="#n125" type="note">[125]</a></p><p>This chapter uses only a subset of the ZThread library, in order to convey the fundamental ideas of threading. The ZThread library contains significantly more sophisticated thread support than is shown here, and you should study that library further in order to fully understand its capabilities.</p></section><section><title><p>Installing ZThreads</p></title><p>Please note that the ZThread library is an independent project and is not supported by the authors of this book; we are simply using the library in this chapter and cannot provide technical support for installation issues. See the ZThread web site for installation support and error reports.</p><p>The ZThread library is distributed as source code. After downloading it from the ZThread web site, you must first compile the library, and then configure your project to use the library.</p><p>The preferred method for compiling ZThreads for most flavors of UNIX (Linux, SunOS, Cygwin, etc.) is to use the configure script. After unpacking the files (using <strong>tar</strong>), simply execute:</p><p>./configure &amp;&amp; make install</p><empty-line/><p>from the main directory of the ZThreads archive to compile and install a copy of the library in the <emphasis>/usr/local</emphasis> directory. You can customize a number of options when using this script, including the locations of files. For details, use this command:</p><p>./configure –help</p><empty-line/><p>The ZThreads code is structured to simplify compilation for other platforms and compilers (such as Borland, Microsoft, and Metrowerks). To do this, create a new project and add all the <emphasis>.cxx </emphasis>files in the <emphasis>src</emphasis> directory of the ZThreads archive to the list of files to be compiled. Also, be sure to include the <emphasis>include</emphasis> directory of the archive in the header search path for your project. The exact details will vary from compiler to compiler so you’ll need to be somewhat familiar with your toolset to be able to use this option.</p><p>Once the compilation has succeeded, the next step is to create a project that uses the newly compiled library. First, let the compiler know where the headers are located so that your <strong>#include</strong> statements will work properly. Typically, you will add an option such as the following to your project:</p><p>-I/path/to/installation/include</p><empty-line/><p>If you used the <emphasis>configure</emphasis> script, the installation path will be whatever you selected for the prefix (which defaults to <emphasis>/usr/local</emphasis>). If you used one of the project files in the <emphasis>build</emphasis> directory, the installation path would simply be the path to the main directory of the ZThreads archive.</p><p>Next, you’ll need to add an option to your project that will let the linker know where to find the library. If you used the configure script, this will look like:</p><p>-L/path/to/installation/lib –lZThread</p><empty-line/><p>If you used one of the project files provided, this will look like:</p><p>-L/path/to/installation/Debug ZThread.lib</p><empty-line/><p>Again, if you used the <emphasis>configure</emphasis> script, the installation path will be whatever you selected for the prefix. If you used a provided project file, the path will be the path to the main directory of the ZThreads archive.</p><p>Note that if you’re using Linux, or if you are using Cygwin (www.cygwin.com) under Windows, you may not need to modify your include or library path; the installation process and defaults will often take care of everything for you.</p><p>Under Linux, you will probably need to add the following to your <strong>.bashrc</strong> so that the runtime system can find the shared library file <strong>LibZThread-x.x.so.O </strong>when it executes the programs in this chapter:</p><p><strong>export LD_LIBRARY_PATH=/usr/local/lib:${LD_LIBRARY_PATH}</strong></p><p>(Assuming you used the default installation process and the shared library ended up in /user/local/lib; otherwise, change the path to your location).</p></section></section><section><title><p>Defining Tasks</p></title><p>A thread carries out a task, so you need a way to describe that task. The <strong>Runnable</strong> class provides a common interface to execute any arbitrary task. Here is the core of the ZThread <strong>Runnable</strong> class, which you will find in <strong>Runnable.h</strong> in the <emphasis>include</emphasis> directory, after installing the ZThread library:</p><p>class Runnable {</p><p>public:</p><p>  virtual void run() = 0;</p><p>  virtual ~Runnable() {}</p><p>};</p><empty-line/><p>By making this a pure abstract base class (or as pure as possible, given the constraints on virtual destructors), <strong>Runnable</strong> allows an easy mixin combination with a base class and other classes.</p><p>To define a task, simply inherit from the <strong>Runnable</strong> class and override <strong>run( )</strong> to make the task do your bidding.</p><p>For example, the following <strong>LiftOff</strong> task displays the countdown before liftoff:</p><p>//: C11:LiftOff.h</p><p>// Demonstration of the Runnable interface.</p><p>#ifndef LIFTOFF_H</p><p>#define LIFTOFF_H</p><p>#include "zthread/Runnable.h"</p><p>#include &lt;iostream&gt;</p><empty-line/><p>class LiftOff : public ZThread::Runnable {</p><p>  int countDown;</p><p>  int id;</p><p>public:</p><p>  LiftOff(int count, int ident = 0) :</p><p>    countDown(count), id(ident) {}</p><p>  ~LiftOff() {</p><p>    std::cout &lt;&lt; id &lt;&lt; " completed" &lt;&lt; std::endl;</p><p>  }</p><p>  void run() {</p><p>    while(countDown--)</p><p>      std::cout &lt;&lt; id &lt;&lt; ":" &lt;&lt; countDown &lt;&lt; std::endl;</p><p>    std::cout &lt;&lt; "Liftoff!" &lt;&lt; std::endl;</p><p>  }</p><p>};</p><p>#endif // LIFTOFF_H ///:~</p><empty-line/><p>As usual, we are careful not to use any <strong>using namespace</strong> directives in a header file. The identifier <strong>id </strong>allows you to distinguish between multiple instances of the task. If you only make a single instance, you can use the default value for <strong>ident</strong>. The destructor will allow you to see that a task is properly destroyed.</p><p>In the following example, the task’s <strong>run( )</strong> is not driven by a separate thread; it is simply called directly in <strong>main( )</strong>:</p><p>//: C11:NoThread.cpp</p><p>#include "LiftOff.h"</p><empty-line/><p>int main() {</p><p>  LiftOff launch(10);</p><p>  launch.run();</p><p>} ///:~</p><empty-line/><p>When a class inherits <strong>Runnable</strong>, it must have a <strong>run( )</strong> function, but that’s nothing special—it doesn’t produce any innate threading abilities.</p><p>To achieve threading behavior, you must use the <strong>Thread</strong> class.</p></section><section><title><p>Using Threads</p></title><section><p>To drive a <strong>Runnable</strong> object with a thread, you create a separate <strong>Thread</strong> object and hand a <strong>Runnable</strong> pointer to the <strong>Thread</strong>’s constructor. This performs the thread initialization and then calls the <strong>Runnable</strong>’s <strong>run( )</strong> as an interruptible thread. By driving <strong>LiftOff</strong> with a <strong>Thread</strong>, the example below shows how any task can be run in the context of another thread:</p><p>//: C11:BasicThreads.cpp</p><p>// The most basic use of the Thread class.</p><p>//{L} ZThread</p><p>#include "LiftOff.h"</p><p>#include "zthread/Thread.h"</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  try {</p><p>    Thread t(new LiftOff(10));</p><p>    cout &lt;&lt; "Waiting for LiftOff" &lt;&lt; endl;</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p><strong>Synchronization_Exception</strong> is part of the ZThread library and is the base class for all ZThread exceptions. It will be thrown if there is an error starting or using a thread.</p><p>A <strong>Thread</strong> constructor only needs a pointer to a <strong>Runnable</strong> object. It will perform the necessary initialization, call that <strong>Runnable</strong>’s <strong>run( )</strong> member function to start the task, and then <emphasis>return to the calling thread</emphasis>, which in this case is the thread for <strong>main( )</strong>. In effect, you have made a member function call to <strong>LiftOff::run( )</strong>, and that function has not yet finished, but you can still perform other operations in the <strong>main( )</strong> thread. (This ability is not restricted to the <strong>main( )</strong> thread—any thread can start another thread.) You can see this by running the program. Even though <strong>LiftOff::run( )</strong> has been called, the "Waiting for LiftOff" message will appear before the countdown has completed. Thus, the program is running two functions at once—<strong>LiftOff::run( )</strong> and <strong>main( )</strong>.</p><p>You can easily add more threads to drive more tasks. Here, you can see how all the threads run in concert with one another:</p><p>//: C11:MoreBasicThreads.cpp</p><p>// Adding more threads.</p><p>//{L} ZThread</p><p>#include "LiftOff.h"</p><p>#include "zthread/Thread.h"</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  const int sz = 5;</p><p>  try {</p><p>    for(int i = 0; i &lt; sz; i++)</p><p>      Thread t(new LiftOff(10, i));</p><p>    cout &lt;&lt; "Waiting for LiftOff" &lt;&lt; endl;</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>The second argument for the <strong>LiftOff</strong> constructor identifies each task. When you run the program, you’ll see that the execution of the different tasks is mixed together as the threads are swapped in and out. This swapping is automatically controlled by the thread scheduler. If you have multiple processors on your machine, the thread scheduler will quietly distribute the threads among the processors.</p><p>The <strong>for</strong> loop can seem a little strange at first, because <strong>t</strong> is being created locally inside the <strong>for</strong> loop and then immediately goes out of scope and is therefore destroyed. This makes it appear that the thread itself might be immediately lost, but you can see from the output that the threads are indeed running to conclusion. When you create a <strong>Thread</strong> object, the associated thread is registered with the threading system, which keeps it alive. Even though the stack-based <strong>Thread</strong> object is lost, the thread itself lives on until its associated task completes. Although this may be counterintuitive from a C++ standpoint, the concept of threads is a departure from the norm: a thread creates a separate thread of execution that persists after the function call ends. This departure is reflected in the persistence of the underlying thread after the object vanishes.</p></section><section><title><p>Creating responsive user interfaces</p></title><p>As stated earlier, one of the motivations for using threading is to create a responsive user interface. Although we don’t cover <emphasis>graphical </emphasis>user interfaces in this book, you can still see a simple example of a console-based user interface.</p><p>The following example reads lines from a file and prints them to the console, <emphasis>sleeping</emphasis> (suspending the current thread) for a second after each line is displayed. (You’ll learn more about sleeping later in the chapter). During this process, the program doesn’t look for user input, so the UI is unresponsive:</p><p>//: C11:UnresponsiveUI.cpp</p><p>// Lack of threading produces an unresponsive UI.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;fstream&gt;</p><p>using namespace std;</p><p>using namespace ZThread;</p><empty-line/><p>int main() {</p><p>  const int sz = 100; // Buffer size;</p><p>  char buf[sz];</p><p>  cout &lt;&lt; "Press &lt;Enter&gt; to quit:" &lt;&lt; endl;</p><p>  ifstream file("UnresponsiveUI.cpp");</p><p>  while(file.getline(buf, sz)) {</p><p>    cout &lt;&lt; buf &lt;&lt; endl;</p><p>    Thread::sleep(1000); // Time in milliseconds</p><p>  }</p><p>  // Read input from the console</p><p>  cin.get();</p><p>  cout &lt;&lt; "Shutting down..." &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>To make the program responsive, you can execute a task that displays the file in a separate thread. The main thread can then watch for user input so the program becomes responsive:</p><p>//: C11:ResponsiveUI.cpp</p><p>// Threading for a responsive user interface.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;fstream&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class DisplayTask : public Runnable {</p><p>  ifstream in;</p><p>  static const int sz = 100;</p><p>  char buf[sz];</p><p>  bool quitFlag;</p><p>public:</p><p>  DisplayTask(const string&amp; file) : quitFlag(false) {</p><p>    in.open(file.c_str());</p><p>  }</p><p>  ~DisplayTask() { in.close(); }</p><p>  void run() {</p><p>    while(in.getline(buf, sz) &amp;&amp; !quitFlag) {</p><p>      cout &lt;&lt; buf &lt;&lt; endl;</p><p>      Thread::sleep(1000);</p><p>    }</p><p>  }</p><p>  void stop() { quitFlag = true; }</p><p>};</p><empty-line/><p>int main() {</p><p>  try {</p><p>    cout &lt;&lt; "Press &lt;Enter&gt; to quit:" &lt;&lt; endl;</p><p>    DisplayTask* dt = new DisplayTask("ResponsiveUI.cpp");</p><p>    Thread t(dt);</p><p>    cin.get();</p><p>    dt-&gt;stop();</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>  cout &lt;&lt; "Shutting down..." &lt;&lt; endl;</p><p>} ///:~</p><empty-line/><p>Now the main thread can respond immediately when you press &lt;Return&gt; and call <strong>stop( )</strong> on the <strong>DisplayTask</strong>.</p><p>This example also shows the need for communication between tasks—the task in the main thread needs to tell the <strong>DisplayTask</strong> to shut down. Of course, since we have a pointer to the <strong>DisplayTask</strong>, you might think of just calling <strong>delete</strong> on that pointer to kill the task, but this produces unreliable programs. The problem is that the task could be in the middle of something important when you destroy it, and so you are likely to put the program in an unstable state. Here, the task itself decides when it’s safe to shut down. The easiest way to do this is by simply notifying the task that you’d like it to stop by setting a Boolean flag. When the task gets to a stable point it can check that flag and do whatever is necessary to clean up before returning from <strong>run( )</strong>. When the task returns from <strong>run( )</strong>, the <strong>Thread</strong> knows that the task has completed.</p><p>Although this program is simple enough that it should not have any problems, there are some small flaws regarding inter-task communication. This is an important topic that will be covered later in this chapter.</p></section><section><title><p>Simplifying with Executors</p></title><p>You can simplify your coding overhead by using ZThread <emphasis>Executors</emphasis>. Executors provide a layer of indirection between a client and the execution of a task; instead of a client executing a task directly, an intermediate object executes the task.</p><p>We can show this by using an <strong>Executor</strong> instead of explicitly creating <strong>Thread</strong> objects in <strong>MoreBasicThreads.cpp</strong>. A <strong>LiftOff</strong> object knows how to run a specific task; like the <emphasis>Command Pattern</emphasis>, it exposes a single function to be executed. An <strong>Executor</strong> object knows how build the appropriate context to execute <strong>Runnable</strong> objects. In the following example, the <strong>ThreadedExecutor</strong> creates one thread per task:</p><p>//: c11:ThreadedExecutor.cpp</p><p>//{L} ZThread</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include "LiftOff.h"</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  try {</p><p>    ThreadedExecutor executor;</p><p>    for(int i = 0; i &lt; 5; i++)</p><p>      executor.execute(new LiftOff(10, i));</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>Note that in some cases a single <strong>Executor</strong> can be used to create and manage all the threads in your system. You must still place the threading code inside a <strong>try</strong> block because an <strong>Executor</strong>’s <strong>execute( )</strong> function may throw <strong>Synchronization_Exception</strong>s if something goes wrong. This is true for any function that involves changing the state of a synchronization object (starting threads, acquiring mutexes, waiting on conditions, etc.), as you will learn later in this chapter.</p><p>The program will exit as soon as all the tasks in the <strong>Executor</strong> complete.</p><p>In the previous example, the <strong>ThreadedExecutor</strong> creates a thread for each task that you want to run, but you can easily change the way these tasks are executed by replacing the <strong>ThreadedExecutor</strong> with a different type of <strong>Executor</strong>. In this chapter, using a <strong>ThreadedExecutor</strong> is fine, but in production code it might result in excessive costs from the creation of too many threads. In that case, you can replace it with a <strong>PoolExecutor</strong>, which will use a limited set of threads to execute the submitted tasks in parallel:</p><p>//: C11:PoolExecutor.cpp</p><p>//{L} ZThread</p><p>#include "zthread/PoolExecutor.h"</p><p>#include "LiftOff.h"</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  try {</p><p>    // Constructor argument is minimum number of threads:</p><p>    PoolExecutor executor(5);</p><p>    for(int i = 0; i &lt; 5; i++)</p><p>      executor.execute(new LiftOff(10, i));</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>With the <strong>PoolExecutor</strong>, you do expensive thread allocation once, up front, and the threads are reused when possible. This saves time because you aren’t constantly paying for thread creation overhead for every single task. Also, in an event-driven system, events that require threads to handle them can be generated as quickly as you want by simply fetching them from the pool. You don’t overrun the available resources because the <strong>PoolExecutor</strong> uses a bounded number of <strong>Thread</strong> objects. Thus, although this book will use <strong>ThreadedExecutor</strong>s, consider using <strong>PoolExecutor</strong>s in production code.</p><p>A <strong>ConcurrentExecutor</strong> is like a <strong>PoolExecutor</strong> with a fixed size of one thread. This is useful for anything you want to run in another thread continually (a long-lived task), such as a task that listens to incoming socket connections. It is also handy for short tasks that you want to run in a thread, for example, small tasks that update a local or remote log, or for an event-dispatching thread.</p><p>If more than one task is submitted to a <strong>ConcurrentExecutor</strong>, each task will run to completion before the next task is begun, all using the same thread. In the following example, you’ll see each task completed, in the order that it was submitted, before the next one is begun. Thus, a <strong>ConcurrentExecutor</strong> serializes the tasks that are submitted to it.</p><p>//: C11:ConcurrentExecutor.cpp</p><p>//{L} ZThread</p><p>#include "zthread/ConcurrentExecutor.h"</p><p>#include "LiftOff.h"</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  try {</p><p>    ConcurrentExecutor executor;</p><p>    for(int i = 0; i &lt; 5; i++)</p><p>      executor.execute(new LiftOff(10, i));</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>Like a <strong>ConcurrentExecutor</strong>, a <strong>SynchronousExecutor</strong> is used when you want only one task at a time to run, serially instead of concurrently. Unlike <strong>ConcurrentExecutor</strong>, a <strong>SynchronousExecutor</strong> doesn’t create or manage threads on it own. It uses the thread that submits the task and thus only acts as a focal point for synchronization. If you have <strong>n</strong> threads submitting tasks to a <strong>SynchronousExecutor</strong>, those threads are all blocked on <strong>execute( )</strong>. One by one they will be allowed to continue as the previous tasks in the queue complete, but no two tasks are ever run at once.</p><p>For example, suppose you have a number of threads running tasks that use the file system, but you are writing portable code so you don’t want to use <strong>flock( )</strong> or another OS-specific call to lock a file. You can run these tasks with a <strong>SynchronousExecutor</strong> to ensure that only one task at a time is running from any thread. This way, you don’t have to deal with synchronizing on the shared resource (and you won’t clobber the file system in the meantime). A better solution is to actually synchronize on the resource (which you’ll learn about later in this chapter), but a <strong>SynchronousExecutor</strong> lets you skip the trouble of getting coordinated properly just to prototype something.</p><p>//: C11:SynchronousExecutor.cpp</p><p>//{L} ZThread</p><p>#include "zthread/SynchronousExecutor.h"</p><p>#include "LiftOff.h"</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>int main() {</p><p>  try {</p><p>    SynchronousExecutor executor;</p><p>    for(int i = 0; i &lt; 5; i++)</p><p>      executor.execute(new LiftOff(10, i));</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>When you run the program, you’ll see that the tasks are executed in the order they are submitted, and each task runs to completion before the next one starts. What you don’t see is that no new threads are created—the <strong>main( ) </strong>thread is used for each task, since in this example, that’s the thread that submits all the tasks. Because <strong>SynchronousExecutor</strong> is primarily for prototyping, you may not use it much in production code.</p></section><section><title><p>Yielding</p></title><p>If you know that you’ve accomplished what you need to during one pass through a loop in your <strong>run( )</strong> function (most <strong>run( )</strong> functions involve a long-running loop), you can give a hint to the thread scheduling mechanism that you’ve done enough and that some other thread might as well have the CPU. This hint (and it <emphasis>is</emphasis> a hint—there’s no guarantee your implementation will listen to it) takes the form of the <strong>yield( )</strong> function.</p><p>We can make a modified version of the <strong>LiftOff</strong> examples by yielding after each loop:</p><p>//: C11:YieldingTask.cpp</p><p>// Suggesting when to switch threads with yield().</p><p>//{L} ZThread</p><p>#include &lt;iostream&gt;</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class YieldingTask : public Runnable {</p><p>  int countDown;</p><p>  int id;</p><p>public:</p><p>  YieldingTask(int ident = 0) : countDown(5), id(ident) {}</p><p>  ~YieldingTask() {</p><p>    cout &lt;&lt; id &lt;&lt; " completed" &lt;&lt; endl;</p><p>  }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const YieldingTask&amp; yt) {</p><p>    return os &lt;&lt; "#" &lt;&lt; yt.id &lt;&lt; ": " &lt;&lt; yt.countDown;</p><p>  }</p><p>  void run() {</p><p>    while(true) {</p><p>      cout &lt;&lt; *this &lt;&lt; endl;</p><p>      if(--countDown == 0) return;</p><p>      Thread::yield();</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  try {</p><p>    ThreadedExecutor executor;</p><p>    for(int i = 0; i &lt; 5; i++)</p><p>      executor.execute(new YieldingTask(i));</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>You can see that the task’s <strong>run( ) </strong>member function consists entirely of an infinite loop. By using <strong>yield( )</strong>, the output is evened up quite a bit over that without yielding. Try commenting out the call to <strong>Thread::yield( )</strong> to see the difference. In general, however, <strong>yield( ) </strong>is useful only in rare situations, and you can’t rely on it to do any serious tuning of your application.</p></section><section><title><p>Sleeping</p></title><p>Another way you can control the behavior of your threads is by calling <strong>sleep( )</strong> to cease execution of that thread for a given number of milliseconds. In the preceding example, if you replace the call to <strong>yield( )</strong> with a call to <strong>sleep( )</strong>, you get the following:</p><p>//: C11:SleepingTask.cpp</p><p>// Calling sleep() to pause for awhile.</p><p>//{L} ZThread</p><p>#include &lt;iostream&gt;</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class SleepingTask : public Runnable {</p><p>  int countDown;</p><p>  int id;</p><p>public:</p><p>  SleepingTask(int ident = 0) : countDown(5), id(ident) {}</p><p>  ~SleepingTask() {</p><p>    cout &lt;&lt; id &lt;&lt; " completed" &lt;&lt; endl;</p><p>  }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const SleepingTask&amp; st) {</p><p>    return os &lt;&lt; "#" &lt;&lt; st.id &lt;&lt; ": " &lt;&lt; st.countDown;</p><p>  }</p><p>  void run() {</p><p>    while(true) {</p><p>      try {</p><p>        cout &lt;&lt; *this &lt;&lt; endl;</p><p>        if(--countDown == 0) return;</p><p>        Thread::sleep(100);</p><p>      } catch(Interrupted_Exception&amp; e) {</p><p>        cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>      }</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  try {</p><p>    ThreadedExecutor executor;</p><p>    for(int i = 0; i &lt; 5; i++)</p><p>      executor.execute(new SleepingTask(i));</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p><strong>Thread::sleep( )</strong> can throw an <strong>Interrupted_Exception</strong> (you’ll learn about interrupts later), and you can see that this is caught in <strong>run( )</strong>. But the task is created and executed inside a <strong>try</strong> block in <strong>main( )</strong> that catches <strong>Synchronization_Exception</strong> (the base class for all ZThread exceptions), so wouldn’t it be possible to just ignore the exception in <strong>run( )</strong> and assume that it will propagate to the handler in <strong>main( )</strong>? This won’t work because exceptions won’t propagate across threads back to <strong>main( )</strong>. Thus, you must handle any exceptions locally that may arise within a task.</p><p>You’ll notice that the threads tend to run in any order, which means that <strong>sleep( )</strong> is also not a way for you to control the order of thread execution. It just stops the execution of the thread for awhile. The only guarantee that you have is that the thread will sleep at least 100 milliseconds (in this example), but it may take longer before the thread resumes execution, because the thread scheduler still has to get back to it after the sleep interval expires.</p><p>If you must control the order of execution of threads, your best bet is to use synchronization controls (described later) or, in some cases, not to use threads at all, but instead to write your own cooperative routines that hand control to each other in a specified order.</p></section><section><title><p>Priority</p></title><p>The <emphasis>priority</emphasis> of a thread tells the scheduler how important this thread is. Although the order that the CPU runs a set of threads is indeterminate, the scheduler will <emphasis>lean</emphasis> toward running the waiting thread with the highest priority first. However, this doesn’t mean that threads with lower priority aren’t run (that is, you can’t get deadlocked because of priorities). Lower priority threads just tend to run less often.</p><p>Here’s <strong>MoreBasicThreads.cpp</strong> modified so that the priority levels are demonstrated. The priorities are adjusting by using <strong>Thread</strong>’s <strong>setPriority( )</strong> function.</p><p>//: C11:SimplePriorities.cpp</p><p>// Shows the use of thread priorities.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;cmath&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class SimplePriorities : public Runnable {</p><p>  int countDown;</p><p>  volatile double d; // No optimization</p><p>  int id;</p><p>public:</p><p>  SimplePriorities(int ident = 0): countDown(5),id(ident){}</p><p>  ~SimplePriorities() throw() {</p><p>    cout &lt;&lt; id &lt;&lt; " completed" &lt;&lt; endl;</p><p>  }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const SimplePriorities&amp; sp) {</p><p>    return os &lt;&lt; "#" &lt;&lt; sp.id &lt;&lt; " priority: " </p><p>      &lt;&lt; Thread().getPriority() </p><p>      &lt;&lt; " count: "&lt;&lt; sp.countDown;</p><p>  }</p><p>  void run() {</p><p>    while(true) {</p><p>      // An expensive, interruptable operation:</p><p>      for(int i = 1; i &lt; 100000; i++)</p><p>        d = d + (M_PI + M_E) / (double)i;</p><p>      cout &lt;&lt; *this &lt;&lt; endl;</p><p>      if(--countDown == 0) return;</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  try {</p><p>    Thread high(new SimplePriorities);</p><p>    high.setPriority(High);</p><p>    for(int i = 0; i &lt; 5; i++) { </p><p>      Thread low(new SimplePriorities(i));</p><p>      low.setPriority(Low);</p><p>    }</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>Here, <strong>operator&lt;&lt;( )</strong> is overridden to display the identifier, priority, and <strong>countDown</strong> value of the task.</p><p>You can see that the priority level of thread <strong>high</strong> is at the highest level, and all the rest of the threads are at the lowest level. We are not using an <strong>Executor</strong> in this example because we need direct access to the threads in order to set their priorities.</p><p>Inside <strong>SimplePriorities::run( )</strong>, 100,000 repetitions of a rather expensive floating-point calculation are performed, involving <strong>double</strong> addition and division. The variable <strong>d</strong> is <strong>volatile</strong> to ensure that no optimization is performed. Without this calculation, you don’t see the effect of setting the priority levels. (Try it: comment out the <strong>for</strong> loop containing the <strong>double</strong> calculations.) With the calculation, you see that thread <strong>high</strong> is given a higher preference by the thread scheduler. (At least, this was the behavior on a Windows machine.) The calculation takes long enough that the thread scheduling mechanism jumps in, changes threads, and pays attention to the priorities so that thread <strong>h</strong> gets preference.</p><p>You can also read the priority of an existing thread with <strong>getPriority( ) </strong>and change it at any time (not just before the thread is run, as in <strong>SimplePriorities.cpp</strong>) with <strong>setPriority( )</strong>.</p><p>Mapping priorities to operating systems is problematic. For example, Windows 2000 has seven priority levels that are not fixed, so the mapping is indeterminate; Sun’s Solaris has 2<sup>31 </sup>levels. The only portable approach is to stick to very large priority granulations, such as the <strong>Low</strong>, <strong>Medium</strong>, and <strong>High</strong> used in the ZThread library.</p></section></section><section><title><p>Sharing limited resources</p></title><section><p>You can think of a single-threaded program as one lonely entity moving around through your problem space and doing one thing at a time. Because there’s only one entity, you never have to think about the problem of two entities trying to use the same resource at the same time: problems such as two people trying to park in the same space, walk through a door at the same time, or even talk at the same time.</p><p>With multithreading, things aren’t lonely anymore, but you now have the possibility of two or more threads trying to use the same resource at once. This can cause two different kinds of problems. The first is that the necessary resources may not exist. In C++, the programmer has complete control over the lifetime of objects, and it’s easy to create threads that try to use objects that get destroyed before those threads complete.</p><p>The second problem is that two or more threads may collide when they try to access the same resource at the same time. If you don’t prevent such a collision, you’ll have two threads trying to access the same bank account at the same time, print to the same printer, adjust the same valve, and so on.</p><p>This section introduces the problem of objects that vanish while tasks are still using them and the problem of tasks colliding over shared resources. You’ll learn about the tools that are used to solve these problems.</p></section><section><title><p>Ensuring the existence of objects</p></title><p>Memory and resource management are major concerns in C++. When you create any C++ program, you have the option of creating objects on the stack or on the heap (using <strong>new</strong>). In a single-threaded program, it’s usually easy to keep track of object lifetimes so that you don’t try to use objects that are already destroyed.</p><p>The examples shown in this chapter create <strong>Runnable</strong> objects on the heap using <strong>new</strong>, but you’ll notice that these objects are never <emphasis>explicitly</emphasis> deleted. However, you can see from the output when you run the programs that the thread library keeps track of each task and eventually deletes it, because the destructors for the tasks are called. This happens when the <strong>Runnable::run( ) </strong>member function completes—returning from <strong>run( )</strong> tells the thread that the task is finished.</p><p>Burdening the thread with deleting a task is a problem. That thread doesn’t necessarily know if another thread still needs to make a reference to that <strong>Runnable</strong>, and so the <strong>Runnable</strong> may be prematurely destroyed. To deal with this problem, tasks in ZThreads are automatically reference-counted by the ZThread library mechanism. A task is maintained until the reference count for that task goes to zero, at which point the task is deleted. This means that tasks must always be deleted dynamically, and so they cannot be created on the stack. Instead, tasks must always be created using <strong>new</strong>, as you see in all the examples in this chapter.</p><p>Often you must also ensure that non-task objects stay alive as long as tasks need them. Otherwise, it’s easy for objects that are used by tasks to go out of scope before those tasks are completed. If this happens, the tasks will try to access illegal storage and will cause program faults. Here’s a simple example:</p><p>//: C11:Incrementer.cpp</p><p>// Destroying objects while threads are still</p><p>// running will cause serious problems.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include &lt;iostream&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class Count {</p><p>  static const int sz = 100;</p><p>  int n[sz];</p><p>public:</p><p>  void increment() {</p><p>    for(int i = 0; i &lt; sz; i++)</p><p>      n[i]++;</p><p>  }</p><p>};</p><empty-line/><p>class Incrementer : public Runnable {</p><p>  Count* count;</p><p>public:</p><p>  Incrementer(Count* c) : count(c) {}</p><p>  void run() {</p><p>    for(int n = 100; n &gt; 0; n--) {</p><p>      Thread::sleep(250);</p><p>      count-&gt;increment();</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  cout &lt;&lt; "This will cause a segmentation fault!" &lt;&lt; endl;</p><p>  Count count;</p><p>  try {</p><p>    Thread t0(new Incrementer(&amp;count));</p><p>    Thread t1(new Incrementer(&amp;count));</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>The <strong>Count</strong> class may seem like overkill at first, but if <strong>n</strong> is only a single <strong>int</strong> (rather than an array), the compiler can put it into a register and that storage will still be available (albeit technically illegal) after the <strong>Count</strong> object goes out of scope. It’s difficult to detect the memory violation in that case. Your results may vary depending on your compiler and operating system, but try making it <strong>n</strong> single <strong>int</strong> and see what happens. In any event, if <strong>Count</strong> contains an array of <strong>int</strong>s as above, the compiler is forced to put it on the stack and not in a register.</p><p><strong>Incrementer</strong> is a simple task that uses a <strong>Count</strong> object. In <strong>main( )</strong>, you can see that the <strong>Incrementer</strong> tasks are running for long enough that the <strong>Count</strong> object will go out of scope, and so the tasks try to access an object that no longer exists. This produces a program fault.</p><p>To fix the problem, we must guarantee that any objects shared between tasks will be around as long as those tasks need them. (If the objects were not shared, they could be composed directly into the task’s class and thus tie their lifetime to that task.) Since we don’t want the static program scope to control the lifetime of the object, we put the object on the heap. And to make sure that the object is not destroyed until there are no other objects (tasks, in this case) using it, we use reference counting.</p><p>Reference counting was explained thoroughly in volume one of this book and further revisited in this volume. The ZThread library includes a template called <strong>CountedPtr</strong> that automatically performs reference counting and <strong>delete</strong>s an object when the reference count goes to zero. Here’s the above program modified to use <strong>CountedPtr</strong> to prevent the fault:</p><p>//: C11:ReferenceCounting.cpp</p><p>// A CountedPtr prevents too-early destruction.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/CountedPtr.h"</p><p>#include &lt;iostream&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class Count {</p><p>  static const int sz = 100;</p><p>  int n[sz];</p><p>public:</p><p>  void increment() {</p><p>    for(int i = 0; i &lt; sz; i++)</p><p>      n[i]++;</p><p>  }</p><p>};</p><empty-line/><p>class Incrementer : public Runnable {</p><p>  CountedPtr&lt;Count&gt; count;</p><p>public:</p><p>  Incrementer(const CountedPtr&lt;Count&gt;&amp; c ) : count(c) {}</p><p>  void run() {</p><p>    for(int n = 100; n &gt; 0; n--) {</p><p>      Thread::sleep(250);</p><p>      count-&gt;increment();</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  CountedPtr&lt;Count&gt; count(new Count);</p><p>  try {</p><p>    Thread t0(new Incrementer(count));</p><p>    Thread t1(new Incrementer(count));</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p><strong>Incrementer</strong> now contains a <strong>CountedPtr</strong> object, which manages a <strong>Count</strong>. In <strong>main( )</strong>, the <strong>CountedPtr</strong> objects are passed into the two <strong>Incrementer</strong> objects by value, so the copy-constructor is called, increasing the reference count. As long as the tasks are still running, the reference count will be nonzero, and so the <strong>Count</strong> object managed by the <strong>CountedPtr</strong> will not be destroyed. Only when all the tasks using the <strong>Count</strong> are completed will <strong>delete</strong> be called (automatically) on the <strong>Count</strong> object by the <strong>CountedPtr</strong>.</p><p>Whenever you have objects that are used by more than one task, you’ll almost always need to manage those objects using the <strong>CountedPtr</strong> template in order to prevent problems arising from object lifetime issues.</p></section><section><title><p>Improperly accessing resources</p></title><p>Consider the following example in which one task generates even numbers and other tasks consume those numbers. In this case, the only job of the consumer threads is to check the validity of the even numbers.</p><p>We’ll first define <strong>EvenChecker</strong>, the consumer thread, since it will be reused in all the subsequent examples. To decouple <strong>EvenChecker</strong> from the various types of generators that we will experiment with, we’ll create an interface called <strong>Generator</strong>, which contains the minimum necessary functions that <strong>EvenChecker</strong> must know about: that it has a <strong>nextValue( )</strong> function and that it can be canceled.</p><p>//: C11:EvenChecker.h</p><p>#ifndef EVENCHECKER_H</p><p>#define EVENCHECKER_H</p><p>#include "zthread/CountedPtr.h"</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/Cancelable.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include &lt;iostream&gt;</p><empty-line/><p>class Generator : public ZThread::Cancelable {</p><p>  bool canceled;</p><p>public:</p><p>  Generator() : canceled(false) {}</p><p>  virtual int nextValue() = 0;</p><p>  void cancel() { canceled = true; }</p><p>  bool isCanceled() { return canceled; }</p><p>};</p><empty-line/><p>class EvenChecker : public ZThread::Runnable {</p><p>  ZThread::CountedPtr&lt;Generator&gt; generator;</p><p>  int id;</p><p>public:</p><p>  EvenChecker(ZThread::CountedPtr&lt;Generator&gt;&amp; g, int ident)</p><p>  : generator(g), id(ident) {}</p><p>  ~EvenChecker() {</p><p>    std::cout &lt;&lt; "~EvenChecker " &lt;&lt; id &lt;&lt; std::endl;</p><p>  }</p><p>  void run() {</p><p>    while(!generator-&gt;isCanceled()) {</p><p>      int val = generator-&gt;nextValue();</p><p>      if(val % 2 != 0) {</p><p>        std::cout &lt;&lt; val &lt;&lt; " not even!" &lt;&lt; std::endl;</p><p>        generator-&gt;cancel(); // Cancels all EvenCheckers</p><p>      }</p><p>    }</p><p>  }</p><p>  // Test any type of generator:</p><p>  template&lt;typename GenType&gt; static void test(int n = 10) {</p><p>    std::cout &lt;&lt; "Press Control-C to exit" &lt;&lt; std::endl;</p><p>    try {</p><p>      ZThread::ThreadedExecutor executor;</p><p>      ZThread::CountedPtr&lt;Generator&gt; gp(new GenType);</p><p>      for(int i = 0; i &lt; n; i++)</p><p>        executor.execute(new EvenChecker(gp, i));</p><p>    } catch(ZThread::Synchronization_Exception&amp; e) {</p><p>      std::cerr &lt;&lt; e.what() &lt;&lt; std::endl;</p><p>    }</p><p>  }</p><p>};</p><p>#endif // EVENCHECKER_H ///:~</p><empty-line/><p>The <strong>Generator</strong> class introduces the pure abstract <strong>Cancelable</strong> class, which is part of the ZThread library. The goal of <strong>Cancelable </strong>is to provide a consistent interface to change the state of an object via the <strong>cancel( )</strong> function and to see whether the object has been canceled with the <strong>isCanceled( )</strong> function. Here, the simple approach of a <strong>bool </strong>cancel<strong>ed</strong> flag is used, similar to the <strong>quitFlag</strong> previously seen in <strong>ResponsiveUI.cpp</strong>. Note that in this example the class that is <strong>Cancelable</strong> is not <strong>Runnable</strong>. Instead, all the <strong>EvenChecker</strong> tasks that depend on the <strong>Cancelable</strong> object (the <strong>Generator</strong>) test it to see if it’s been canceled, as you can see in <strong>run( )</strong>. This way, the tasks that share the common resource (the <strong>Cancelable Generator</strong>) watch that resource for the signal to terminate. This eliminates the so-called <emphasis>race condition</emphasis>, in which two or more tasks race to respond to a condition and thus collide or otherwise produce inconsistent results. You must be careful to think about and protect against all the possible ways a concurrent system can fail. For example, a task cannot depend on another task, because there’s no guarantee of the order in which tasks will be shut down. Here, by making tasks depend on non-task objects, we eliminate the potential race condition.</p><p>In later sections, you’ll see that the ZThread library contains more general mechanisms for termination of threads.</p><p>Since multiple <strong>EvenChecker </strong>objects may end up sharing a <strong>Generator</strong>, the <strong>CountedPtr </strong>template is used to reference count the <strong>Generator </strong>objects.</p><p>The last member function in <strong>EvenChecker</strong> is a <strong>static </strong>member template that sets up and performs a test of any type of <strong>Generator</strong> by creating one inside a <strong>CountedPtr</strong> and then starting a number of <strong>EvenChecker</strong>s that use that <strong>Generator</strong>. If the <strong>Generator</strong> causes a failure, <strong>test( )</strong> will report it and return; otherwise, you must press Control-C to terminate it.</p><p><strong>EvenChecker</strong> tasks constantly read and test the values from their associated <strong>Generator</strong>. Note that if <strong>generator-&gt;isCanceled( )</strong> is true, <strong>run( )</strong> returns, which tells the <strong>Executor</strong> in <strong>EvenChecker::test( ) </strong>that the task is complete. Any <strong>EvenChecker</strong> task can call <strong>cancel( ) </strong>on its associated <strong>Generator</strong>, which will cause all other <strong>EvenChecker</strong>s using that <strong>Generator </strong>to gracefully shut down.</p><p>The <strong>EvenGenerator</strong> is simple –<strong>nextValue( )</strong> produces the next even value:</p><p>//: C11:EvenGenerator.cpp</p><p>// When threads collide.</p><p>//{L} ZThread</p><p>#include "EvenChecker.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include &lt;iostream&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class EvenGenerator : public Generator {</p><p>  int currentEvenValue;</p><p>public:</p><p>  EvenGenerator() { currentEvenValue = 0; }</p><p>  ~EvenGenerator() { cout &lt;&lt; "~EvenGenerator" &lt;&lt; endl; }</p><p>  int nextValue() {</p><p>    currentEvenValue++; // Danger point here!</p><p>    currentEvenValue++;</p><p>    return currentEvenValue;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  EvenChecker::test&lt;EvenGenerator&gt;();</p><p>} ///:~</p><empty-line/><p>It’s possible for one thread to call <strong>nextValue( )</strong> after the first increment of <strong>currentEvenValue</strong> and before the second (at the place in the code commented "Danger point here!"), in which case the value would be in an "incorrect" state. To prove that this can happen, <strong>EvenChecker::test( )</strong> creates a group of <strong>EvenChecker</strong> objects to continually read the output of an <strong>EvenGenerator</strong> and test to see if each one is even. If not, the error is reported and the program is shut down.</p><p>This program may not detect the problem until the <strong>EvenGenerator</strong> has completed many cycles, depending on the particulars of your operating system and other implementation details. If you want to see it fail much faster, try putting a call to <strong>yield( )</strong> between the first and second increments. In any event, it <emphasis>will</emphasis> eventually fail because the <strong>EvenChecker</strong> threads are able to access the information in <strong>EvenGenerator</strong> while it’s in an "incorrect" state.</p></section><section><title><p>Controlling access</p></title><p>The previous example shows a fundamental problem when using threads: You never know when a thread might be run. Imagine sitting at a table with a fork, about to spear the last piece of food on your plate, and as your fork reaches for it, the food suddenly vanishes (because your thread was suspended and another task came in and stole the food). That’s the problem you’re dealing with when writing concurrent programs. </p><p>Sometimes you don’t care if a resource is being accessed at the same time you’re trying to use it (the food is on some other plate). But for multithreading to work, you need some way to prevent two threads from accessing the same resource, at least during critical periods.</p><p>Preventing this kind of collision is simply a matter of putting a lock on a resource when one thread is using it. The first thread that accesses a resource locks it, and then the other threads cannot access that resource until it is unlocked, at which time another thread locks and uses it, and so on. If the front seat of the car is the limited resource, the child who shouts "Dibs!" acquires the lock.</p><p>Thus, we need to be able to prevent any other tasks from accessing the storage when that storage is not in a proper state. That is, we need to have a mechanism that <emphasis>excludes</emphasis> a second task from accessing the storage when a first task is already using it. This idea is fundamental to all multithreading systems and is called <emphasis>mutual exclusion</emphasis>; the mechanism used abbreviates this to <emphasis>mutex</emphasis>. The ZThread library contains a mutex mechanism declared in the header <strong>Mutex.h</strong>.</p><p>To solve the problem in the above program, we identify the <emphasis>critical sections</emphasis> in which mutual exclusion must apply; then we <emphasis>acquire</emphasis> the mutex before entering the critical section and <emphasis>release</emphasis> it at the end of the critical section. Only one thread can acquire the mutex at any time, so mutual exclusion is achieved:</p><p>//: C11:MutexEvenGenerator.cpp</p><p>// Preventing thread collisions with mutexes.</p><p>//{L} ZThread</p><p>#include "EvenChecker.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include "zthread/Mutex.h"</p><p>#include &lt;iostream&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class MutexEvenGenerator : public Generator {</p><p>  int currentEvenValue;</p><p>  Mutex lock;</p><p>public:</p><p>  MutexEvenGenerator() { currentEvenValue = 0; }</p><p>  ~MutexEvenGenerator() {</p><p>    cout &lt;&lt; "~MutexEvenGenerator" &lt;&lt; endl;</p><p>  }</p><p>  int nextValue() {</p><p>    lock.acquire();</p><p>    currentEvenValue++;</p><p>    Thread::yield();</p><p>    currentEvenValue++;</p><p>    int rval = currentEvenValue;</p><p>    lock.release();</p><p>    return rval;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  EvenChecker::test&lt;MutexEvenGenerator&gt;();</p><p>} ///:~</p><empty-line/><p>The only changes here are in <strong>MutexEvenGenerator</strong>, which adds a <strong>Mutex</strong> called <strong>lock</strong> and uses <strong>acquire( )</strong> and <strong>release( )</strong> in <strong>nextValue( )</strong>. Note that <strong>nextValue( )</strong> must capture the return value inside the critical section, because if you return from inside the critical section, you won’t release the lock and will thus prevent it from being acquired again. (This usually leads to <emphasis>deadlock</emphasis>, which you’ll learn about at the end of this chapter.)</p><p>The first thread that enters <strong>nextValue( )</strong> acquires the lock, and any further threads that try to acquire the lock are blocked from doing so until the first thread releases the lock. At that point, the scheduling mechanism selects another thread that is waiting on the lock. This way, only one thread at a time can pass through the code that is guarded by the mutex.</p></section><section><title><p>Simplified coding with Guards</p></title><section><p>The use of mutexes rapidly becomes complicated when exceptions are introduced. To make sure that the mutex is always released, you must ensure that each possible exception path includes a call to <strong>release( )</strong>. In addition, any function that has multiple return paths must carefully ensure that it calls <strong>release( )</strong> at the appropriate points.</p><p>These problems can be easily solved by using the fact that a stack-based object has a destructor that is always called regardless of how you exit from a function scope. In the ZThread library, this is implemented as the <strong>Guard</strong> template. The <strong>Guard</strong> template creates objects on the local stack that <strong>acquire( ) </strong>a <strong>Lockable</strong> object when constructed and <strong>release( )</strong> that lock when destroyed. Because the <strong>Guard</strong> object exists on the local stack, it will automatically be destroyed regardless of how the function exits and will therefore always unlock the <strong>Lockable</strong> object. Here’s the above example reimplemented using <strong>Guard</strong>s:</p><p>//: C11:GuardedEvenGenerator.cpp</p><p>// Simplifying mutexes with the Guard template.</p><p>//{L} ZThread</p><p>#include "EvenChecker.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include "zthread/Mutex.h"</p><p>#include "zthread/Guard.h"</p><p>#include &lt;iostream&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class GuardedEvenGenerator : public Generator {</p><p>  int currentEvenValue;</p><p>  Mutex lock;</p><p>public:</p><p>  GuardedEvenGenerator() { currentEvenValue = 0; }</p><p>  ~GuardedEvenGenerator() {</p><p>    cout &lt;&lt; "~GuardedEvenGenerator" &lt;&lt; endl;</p><p>  }</p><p>  int nextValue() {</p><p>    Guard&lt;Mutex&gt; g(lock);</p><p>    currentEvenValue++;</p><p>    Thread::yield();</p><p>    currentEvenValue++;</p><p>    return currentEvenValue;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  EvenChecker::test&lt;GuardedEvenGenerator&gt;();</p><p>} ///:~</p><empty-line/><p>Note that the temporary return value is no longer necessary in <strong>nextValue( )</strong>. In general, there is less code to write, and the opportunity for user error is greatly reduced.</p><p>An interesting feature of the <strong>Guard</strong> template is that it can be used to manipulate other guards safely. For example, a second <strong>Guard</strong> can be used to temporarily unlock a guard:</p><p>//: C11:TemporaryUnlocking.cpp</p><p>// Temporarily unlocking another guard.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/Mutex.h"</p><p>#include "zthread/Guard.h"</p><p>using namespace ZThread;</p><empty-line/><p>class TemporaryUnlocking {</p><p>  Mutex lock;</p><p>public:</p><p>  void f() {</p><p>    Guard&lt;Mutex&gt; g(lock);</p><p>    // lock is acquired</p><p>    // ...</p><p>    {</p><p>      Guard&lt;Mutex, UnlockedScope&gt; h(g);</p><p>      // lock is released</p><p>      // ...</p><p>      // lock is acquired</p><p>    }</p><p>    // ...</p><p>    // lock is released</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  TemporaryUnlocking t;</p><p>  t.f();</p><p>} ///:~</p><empty-line/><p>A Guard can also be used to try to acquire a lock for a certain amount of time and then abort:</p><p>//: C11:TimedLocking.cpp</p><p>// Limited time locking.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/Mutex.h"</p><p>#include "zthread/Guard.h"</p><p>using namespace ZThread;</p><empty-line/><p>class TimedLocking {</p><p>  Mutex lock;</p><p>public:</p><p>  void f() {</p><p>    Guard&lt;Mutex, TimedLockedScope&lt;500&gt; &gt; g(lock);</p><p>    // ...</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  TimedLocking t;</p><p>  t.f();</p><p>} ///:~</p><empty-line/><p>In this example, a <strong>Timeout_Exception</strong> will be thrown if the lock cannot be acquired within 500 milliseconds.</p></section><section><section><title><p>Synchronizing entire classes</p></title><p>The ZThread library also provides a <strong>GuardedClass</strong> template to automatically create a synchronized wrapper for an entire class. This means that every member function in the class will automatically be guarded:</p><p>//: C11:SynchronizedClass.cpp</p><p>//{L} ZThread</p><p>#include "zthread/GuardedClass.h"</p><p>using namespace ZThread;</p><empty-line/><p>class MyClass {</p><p>public:</p><p>  void func1() {}</p><p>  void func2() {}</p><p>};</p><empty-line/><p>int main() {</p><p>  MyClass a;</p><p>  a.func1(); // not synchronized</p><p>  a.func2(); // not synchronized</p><p>  GuardedClass&lt;MyClass&gt; b(new MyClass);</p><p>  // Synchronized calls, only one thread at a time allowed:</p><p>  b-&gt;func1();</p><p>  b-&gt;func2();</p><p>} ///:~</p><empty-line/><p>Object <strong>a</strong> is a not synchronized, so <strong>func1( )</strong> and <strong>func2( )</strong> can be called at any time by any number of threads. Object <strong>b</strong> is protected by the <strong>GuardedClass</strong> wrapper, so each member function is automatically synchronized and only one function per object can be called any time.</p><p>The wrapper locks at a class level of granularity, which may affect performance in some cases. If a class contains some unrelated functions, it may be better to synchronize those functions internally with two different locks. However, if you find yourself doing this, it means that one class contains groups of data that may not be strongly associated. Consider breaking the class into two classes.</p><p>Guarding all member functions of a class with a mutex does not automatically make that class thread-safe. You must carefully consider all threading issues in order to guarantee thread safety.</p></section></section></section><section><title><p>Thread local storage</p></title><p>A second way to eliminate the problem of tasks colliding over shared resources is to eliminate the sharing of variables, which can be done by creating different storage for the same variable, for each different thread that uses an object. Thus, if you have five threads using an object with a variable <strong>x</strong>, <emphasis>thread local storage</emphasis> automatically generates five different pieces of storage for <strong>x</strong>. Fortunately, the creation and management of thread local storage is taken care of automatically by ZThread’s <strong>ThreadLocal</strong> template, as seen here:</p><p>//: C11:ThreadLocalVariables.cpp</p><p>// Automatically giving each thread its own storage.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/Mutex.h"</p><p>#include "zthread/Guard.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include "zthread/Cancelable.h"</p><p>#include "zthread/ThreadLocal.h"</p><p>#include "zthread/CountedPtr.h"</p><p>#include &lt;iostream&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class ThreadLocalVariables : public Cancelable {</p><p>  ThreadLocal&lt;int&gt; value;</p><p>  bool canceled;</p><p>  Mutex lock;</p><p>public:</p><p>  ThreadLocalVariables() : canceled(false) {</p><p>    value.set(0);</p><p>  }</p><p>  void increment() { value.set(value.get() + 1); }</p><p>  int get() { return value.get(); }</p><p>  void cancel() {</p><p>    Guard&lt;Mutex&gt; g(lock);</p><p>    canceled = true;</p><p>  }</p><p>  bool isCanceled() {</p><p>    Guard&lt;Mutex&gt; g(lock);</p><p>    return canceled;</p><p>  }</p><p>};</p><empty-line/><p>class Accessor : public Runnable {</p><p>  int id;</p><p>  CountedPtr&lt;ThreadLocalVariables&gt; tlv;</p><p>public:</p><p>  Accessor(CountedPtr&lt;ThreadLocalVariables&gt;&amp; tl, int idn)</p><p>  : id(idn), tlv(tl) {}</p><p>  void run() {</p><p>    while(!tlv-&gt;isCanceled()) {</p><p>      tlv-&gt;increment();</p><p>      cout &lt;&lt; *this &lt;&lt; endl;</p><p>    }</p><p>  }</p><p>  friend ostream&amp;</p><p>    operator&lt;&lt;(ostream&amp; os, Accessor&amp; a) {</p><p>    return os &lt;&lt; "#" &lt;&lt; a.id &lt;&lt; ": " &lt;&lt; a.tlv-&gt;get();</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  cout &lt;&lt; "Press &lt;Enter&gt; to quit" &lt;&lt; endl;</p><p>  try {</p><p>    CountedPtr&lt;ThreadLocalVariables&gt;</p><p>      tlv(new ThreadLocalVariables);</p><p>    const int sz = 5;</p><p>    ThreadedExecutor executor;</p><p>    for(int i = 0; i &lt; sz; i++)</p><p>      executor.execute(new Accessor(tlv, i));</p><p>    cin.get();</p><p>    tlv-&gt;cancel(); // All Accessors will quit</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>When you create a <strong>ThreadLocal</strong> object by instantiating the template, you are only able to access the contents of the object using the <strong>get( )</strong> and <strong>set( )</strong> functions. The <strong>get( ) </strong>function returns a copy of the object that is associated with that thread, and <strong>set( )</strong> inserts its argument into the object stored for that thread, returning the old object that was in storage. You can see this is use in <strong>increment( )</strong> and <strong>get( )</strong> in <strong>ThreadLocalVariables</strong>.</p><p>Since <strong>tlv</strong> is shared by multiple <strong>Accessor</strong> objects, it is written as <strong>Cancelable</strong> so that the <strong>Accessor</strong>s can be signaled when we want to shut the system down.</p><p>When you run this program, you’ll see evidence that the individual threads are each allocated their own storage.</p></section></section><section><title><p>Terminating tasks</p></title><section><p>In previous examples, we have seen the use of a "quit flag" or the <strong>Cancelable</strong> interface in order to terminate a task. This is a reasonable approach to the problem. However, in some situations the task must be terminated more abruptly. In this section, you’ll learn about the issues and problems of such termination.</p><p>First, let’s look at an example that not only demonstrates the termination problem but is also an additional example of resource sharing. To present this example, we’ll first need to solve the problem of iostream collision</p></section><section><title><p>Preventing iostream collision</p></title><p>You may have noticed in previous examples that the output is sometimes garbled. The problem is that C++ iostreams were not created with threading in mind, and so there’s nothing to keep one thread’s output from interfering with another thread’s output.</p><p>To solve the problem, we need to create the entire output packet first and then explicitly decide when to try to send it to the console. One simple solution is to write the information to an <strong>ostringstream</strong> and then use a single object with a mutex as the point of output among all threads, to prevent more than one thread from writing at the same time:</p><p>//: C11:Display.h</p><p>// Prevents ostream collisions</p><p>#ifndef DISPLAY_H</p><p>#define DISPLAY_H</p><p>#include "zthread/Mutex.h"</p><p>#include "zthread/Guard.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;sstream&gt;</p><empty-line/><p>class Display { // Share one of these among all threads</p><p>  ZThread::Mutex iolock;</p><p>public:</p><p>  void output(std::ostringstream&amp; os) {</p><p>    ZThread::Guard&lt;ZThread::Mutex&gt; g(iolock);</p><p>    std::cout &lt;&lt; os.str();</p><p>  }</p><p>};</p><p>#endif // DISPLAY_H ///:~</p><empty-line/><p>This way, all of the standard <strong>operator&lt;&lt;( )</strong> functions are predefined for us and the object can be built in memory using familiar <strong>ostream</strong> operators. When a task wants to display output, it creates a temporary <strong>ostringstream </strong>object that it uses to build up the desired output message. When it calls <strong>output( )</strong>, the mutex prevents multiple threads from writing to this <strong>Display</strong> object. (You must use only one <strong>Display</strong> object in your program, as you’ll see in the following examples.)</p><p>This just shows the basic idea, but if necessary, you can build a more elaborate framework. For example, you could enforce the requirement that there be only one <strong>Display</strong> object in a program by making it a <emphasis>Singleton</emphasis>. (The ZThread library has a <strong>Singleton</strong> template to support Singletons.)</p></section><section><title><p>The ornamental garden</p></title><section><p>In this simulation, the garden committee would like to know how many people enter the garden each day though its multiple gates. Each gate has a turnstile or some other kind of counter, and after the turnstile count is incremented, a shared count is incremented that represents the total number of people in the garden.</p><p>//: C11:OrnamentalGarden.cpp</p><p>//{L} ZThread</p><p>#include "Display.h"</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/FastMutex.h"</p><p>#include "zthread/Guard.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include "zthread/CountedPtr.h"</p><p>#include &lt;vector&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class Count : public Cancelable {</p><p>  FastMutex lock;</p><p>  int count;</p><p>  bool paused, canceled;</p><p>public:</p><p>  Count() : count (0), paused(false), canceled(false) {</p><p>    srand(time(0)); // Seed the random number generator</p><p>  }</p><p>  int increment() {</p><p>    // Comment the following line to see counting fail:</p><p>    Guard&lt;FastMutex&gt; g(lock);</p><p>    int temp = count ;</p><p>    if(rand() &lt; RAND_MAX/2) // Yield half the time</p><p>      Thread::yield();</p><p>    return (count  = ++temp);</p><p>  }</p><p>  int value() { </p><p>    Guard&lt;FastMutex&gt; g(lock);</p><p>    return count; </p><p>  }</p><p>  void cancel() {</p><p>    Guard&lt;FastMutex&gt; g(lock);</p><p>    canceled = true;</p><p>  }</p><p>  bool isCanceled() {</p><p>    Guard&lt;FastMutex&gt; g(lock);</p><p>    return canceled;</p><p>  }</p><p>  bool pause() {</p><p>    Guard&lt;FastMutex&gt; g(lock);</p><p>    paused = true;</p><p>  }</p><p>  bool isPaused() {</p><p>    Guard&lt;FastMutex&gt; g(lock);</p><p>    return paused;</p><p>  }</p><p>};</p><empty-line/><p>class Entrance : public Runnable {</p><p>  CountedPtr&lt;Count&gt; count;</p><p>  CountedPtr&lt;Display&gt; display;</p><p>  int number;</p><p>  int id;</p><p>  bool waitingForCancel;</p><p>public:</p><p>  Entrance(CountedPtr&lt;Count&gt;&amp; cnt, </p><p>    CountedPtr&lt;Display&gt;&amp; disp, int idn) </p><p>  : count(cnt), display(disp), id(idn), number(0),</p><p>    waitingForCancel(false) {}</p><p>  void run() {</p><p>    while(!count-&gt;isPaused()) {</p><p>      number++;</p><p>      {</p><p>        ostringstream os;</p><p>        os &lt;&lt; *this &lt;&lt; " Total: "</p><p>           &lt;&lt; count-&gt;increment() &lt;&lt; endl;</p><p>        display-&gt;output(os);</p><p>      }</p><p>      Thread::sleep(100);</p><p>    }</p><p>    waitingForCancel = true;</p><p>    while(!count-&gt;isCanceled()) // Hold here...</p><p>      Thread::sleep(100);</p><p>    ostringstream os;</p><p>    os &lt;&lt; "Terminating " &lt;&lt; *this &lt;&lt; endl;</p><p>    display-&gt;output(os);</p><p>  }</p><p>  int getValue() {</p><p>    while(count-&gt;isPaused() &amp;&amp; !waitingForCancel)</p><p>      Thread::sleep(100);</p><p>    return number; </p><p>  }</p><p>  friend ostream&amp;</p><p>  operator&lt;&lt;(ostream&amp; os, const Entrance&amp; e) {</p><p>    return os &lt;&lt; "Entrance " &lt;&lt; e.id &lt;&lt; ": " &lt;&lt; e.number;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  cout &lt;&lt; "Press &lt;ENTER&gt; to quit" &lt;&lt; endl;</p><p>  CountedPtr&lt;Count&gt; count(new Count);</p><p>  vector&lt;Entrance*&gt; v;</p><p>  CountedPtr&lt;Display&gt; display(new Display);</p><p>  const int sz = 5;</p><p>  try {</p><p>    ThreadedExecutor executor;</p><p>    for(int i = 0; i &lt; sz; i++) {</p><p>      Entrance* task = new Entrance(count, display, i);</p><p>      executor.execute(task);</p><p>      // Save the pointer to the task:</p><p>      v.push_back(task);</p><p>    }</p><p>    cin.get(); // Wait for user to press &lt;Enter&gt;</p><p>    count-&gt;pause(); // Causes tasks to stop counting</p><p>    int sum = 0;</p><p>    vector&lt;Entrance*&gt;::iterator it = v.begin();</p><p>    while(it != v.end()) {</p><p>      sum += (*it)-&gt;getValue();</p><p>      it++;</p><p>    }</p><p>    ostringstream os;</p><p>    os &lt;&lt; "Total: " &lt;&lt; count-&gt;value() &lt;&lt; endl</p><p>       &lt;&lt; "Sum of Entrances: " &lt;&lt; sum &lt;&lt; endl;</p><p>    display-&gt;output(os);</p><p>    count-&gt;cancel(); // Causes threads to quit</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p><strong>Count</strong> is the class that keeps the master count of garden visitors. The single <strong>Count</strong> object defined in <strong>main( )</strong> as <strong>count </strong>is held as a <strong>CountedPtr</strong> in <strong>Entrance</strong> and thus is shared by all <strong>Entrance</strong> objects. A <strong>FastMutex</strong> called <strong>lock </strong>is used in this example instead of an ordinary <strong>Mutex</strong> because a <strong>FastMutex</strong> uses the native operating system mutex and will thus yield more interesting results.</p><p>A <strong>Guard</strong> is used with <strong>lock</strong> in <strong>increment( )</strong> to synchronize access to <strong>count</strong>. This function uses <strong>rand( )</strong> to cause a <strong>yield( )</strong> roughly half the time, in between fetching <strong>count</strong> into <strong>temp </strong>and incrementing and storing <strong>temp </strong>back into <strong>count</strong>. Because of this, if you comment out the <strong>Guard</strong> object definition, you will rapidly see the program break because multiple threads will be accessing and modifying <strong>count</strong> simultaneously.</p><p>The <strong>Entrance</strong> class also keeps a local <strong>number</strong> with the number of visitors that have passed through this particular entrance. This provides a double-check against the <strong>count</strong> object to make sure that the proper number of visitors is being recorded. <strong>Entrance::run( )</strong> simply increments <strong>number</strong> and the <strong>count</strong> object and sleeps for 100 milliseconds.</p><p>In main, a <strong>vector&lt;Entrance*&gt;</strong> is loaded with each <strong>Entrance</strong> that is created. After the user presses <strong>&lt;Enter&gt;</strong>, this <strong>vector </strong>is used to iterate over all the individual <strong>Entrance</strong> values and total them.</p><p>This program goes to quite a bit of extra trouble to shut everything down in a stable fashion. Part of the reason for this is to show just how careful you must be when terminating a multithreaded program, and part of the reason is to demonstrate the value of <strong>interrupt( )</strong>, which you will learn about shortly.</p><p>All the communication between the <strong>Entrance</strong> objects takes place through the single <strong>Count</strong> object. When the user presses &lt;Enter&gt;, <strong>main( )</strong> sends the <strong>pause( )</strong> message to <strong>count</strong>. Since each <strong>Entrance::run( )</strong> is watching the <strong>count</strong> object to see whether it is paused, this causes each <strong>Entrance</strong> to move into the <strong>waitingForCancel</strong> state, where it is no longer counting, but it is still alive. This is essential because <strong>main( )</strong> must still be able to safely iterate over each object in the <strong>vector&lt;Entrance*&gt;</strong>. Note that because there is a slight possibility that the iteration might occur before an <strong>Entrance</strong> has finished counting and moved into the <strong>waitingForCancel</strong> state, the <strong>getValue( )</strong> function cycles through calls to <strong>sleep( )</strong> until the object moves into <strong>waitingForCancel</strong>. (This is one form of what is called a <emphasis>busy wait</emphasis>, which is undesirable. You’ll see the preferred approach of using <strong>wait( )</strong> later in the chapter.) Once <strong>main( )</strong> completes its iteration through the <strong>vector&lt;Entrance*&gt;</strong>, the <strong>cancel( )</strong> message is sent to the <strong>count</strong> object, and once again all the <strong>Entrance</strong> objects are watching for this state change. At this point, they print a termination message and exit from <strong>run( )</strong>, which causes each task to be destroyed by the threading mechanism.</p><p>As this program runs, you will see the total count and the count at each entrance displayed as people walk through a turnstile. If you comment out the <strong>Guard</strong> object in <strong>Count::increment( )</strong>, you’ll notice that the total number of people is not what you expect it to be. The number of people counted by each turnstile will be different from the value in <strong>count</strong>. As long as the <strong>Mutex</strong> is there to synchronize access to the <strong>Counter</strong>, things work correctly. Keep in mind that <strong>Count::increment( )</strong> exaggerates the potential for failure by using <strong>temp</strong> and <strong>yield( )</strong>. In real threading problems, the possibility for failure may be statistically small, so you can easily fall into the trap of believing that things are working correctly. Just as in the example above, there are likely to be hidden problems that haven’t occurred to you, so be exceptionally diligent when reviewing concurrent code.</p></section><section><section><title><p>Atomic operations</p></title><p>Note that <strong>Count::value( )</strong> returns the value of <strong>count </strong>using a <strong>Guard</strong> object for synchronization. This brings up an interesting point, because this code will <emphasis>probably</emphasis> work fine with most compilers and systems without synchronization. The reason is that, in general, a simple operation such as returning an <strong>int</strong> will be an <emphasis>atomic operation</emphasis>, which means that it will probably happen in a single microprocessor instruction that will not get interrupted. (The multithreading mechanism is unable to stop a thread in the middle of a microprocessor instruction.) That is, atomic operations are not interruptible by the threading mechanism and thus do not need to be guarded.<a l:href="#n126" type="note">[126]</a> In fact, if we removed the fetch of <strong>count</strong> into <strong>temp</strong> and removed the <strong>yield( )</strong>, and instead simply incremented <strong>count</strong> directly, we probably wouldn’t need a lock at all because the increment operation is <emphasis>usually</emphasis> atomic, as well.</p><p>The problem is that the C++ standard doesn’t guarantee atomicity for any of these operations. Although operations such as returning an <strong>int</strong> and incrementing an <strong>int</strong> are almost certainly atomic on most machines, there’s no guarantee. And because there’s no guarantee, you have to assume the worst. Sometimes you might investigate the atomicity behavior on a particular machine (usually by looking at assembly language) and write code based on those assumptions. That’s always dangerous and ill-advised. It’s too easy for that information to be lost or hidden, and the next person that comes along may assume that this code can be ported to another machine and then go mad tracking down the occasional glitch caused by thread collisions.</p><p>So, while removing the guard on <strong>Count::value( )</strong> seems to work, it’s not airtight, and thus on some machines you may see aberrant behavior.</p></section></section></section><section><title><p>Terminating when blocked</p></title><section><p><strong>Entrance::run( )</strong> in the previous example includes a call to <strong>sleep( )</strong> in the main loop. We know that in that example the sleep will eventually wake up and the task will reach the top of the loop where it has an opportunity to break out of that loop by checking the <strong>isPaused( )</strong> status. However, <strong>sleep( )</strong> is just one situation in which a thread is <emphasis>blocked</emphasis> from executing, and sometimes you must terminate a task that’s blocked.</p></section><section><section><title><p>Thread states</p></title><p>A thread can be in any one of four states:</p><p>1.<emphasis>New</emphasis>: A thread remains in this state only momentarily, as it is being created. It allocates any necessary system resources and performs initialization. At this point it becomes eligible to receive CPU time. The scheduler will then transition this thread to the <emphasis>runnable</emphasis> or <emphasis>blocked</emphasis> state.</p><p>2.<emphasis>Runnable</emphasis>: This means that a thread <emphasis>can</emphasis> be run when the time-slicing mechanism has CPU cycles available for the thread. Thus, the thread might or might not be running at any moment, but there’s nothing to prevent it from being run if the scheduler can arrange it; it’s not dead or blocked.</p><p>3.<emphasis>Blocked</emphasis>: The thread could be run, but something prevents it. (It might be waiting for I/O to complete, for example.) While a thread is in the blocked state, the scheduler will simply skip it and not give it any CPU time. Until a thread reenters the <emphasis>runnable</emphasis> state, it won’t perform any operations.</p><p>4.<emphasis>Dead</emphasis>: A thread in the dead state is no longer schedulable and is not eligible to receive any CPU time. Its task is completed, and it is no longer <emphasis>runnable</emphasis>. The normal way for a thread to die is by returning from its <strong>run( ) </strong>function.</p></section><section><title><p>Becoming blocked</p></title><p>A thread is blocked when it cannot continue running. A thread can become blocked for the following reasons: </p><p>·         You’ve put the thread to sleep by calling <strong>sleep(milliseconds)</strong>, in which case it will not be run for the specified time.</p><p>·         You’ve suspended the execution of the thread with <strong>wait( )</strong>. It will not become runnable again until the thread gets the <strong>signal( )</strong> or <strong>broadcast( )</strong> message. We’ll examine these in a later section.</p><p>·         The thread is waiting for some I/O to complete.</p><p>·         The thread is trying to enter a block of code that is guarded by a mutex, and that mutex has already been acquired by another thread.</p><p>The problem we need to look at now is this: sometimes you want to terminate a thread that is in a blocked state. It can be blocked for any of the reasons in the above list (<emphasis>except </emphasis>for IO, as you’ll see). If you can’t wait for it to get to a point in the code where it can check a state value and decide to terminate on its own, you have to abort the thread out of its blocked state.</p></section></section></section><section><title><p>Interruption</p></title><section><p>As you might imagine, it’s much messier to break out of the middle of a loop than it is to wait for the loop to get to a test of <strong>isCanceled( )</strong> (or some other place where the programmer is ready to leave the loop). When you break out of a blocked task, you might be breaking out of your <strong>run( )</strong> loop in a place where you must destroy objects and clean up resources. Because of this, breaking out of the middle of a <strong>run( )</strong> loop in a task is more like throwing an exception than anything else, so in ZThreads, exceptions are used for this kind of abort. (This walks the fine edge of being an inappropriate use of exceptions because it means you are often using them for control flow.) To return to a known good state when terminating a task this way, carefully consider the execution paths of your code and properly clean up everything inside the <strong>catch</strong> clause. We’ll look at these issues in this section.</p><p>To terminate a blocked thread, the ZThread library provides the <strong>Thread</strong>::<strong>interrupt( )</strong> function. This sets the <emphasis>interrupted status</emphasis> for that thread. A thread with its interrupted status set will throw an <strong>Interrupted_Exception</strong> if it is already blocked or it attempts a blocking operation. The interrupted status will be reset when the exception is thrown or if the task calls <strong>Thread::interrupted( )</strong>. As you’ll see, <strong>Thread::interrupted( )</strong> provides a second way to leave your <strong>run( )</strong> loop, without throwing an exception.</p><p>Here’s an example that shows the basics of <strong>interrupt( )</strong>:</p><p>//: C11:Interrupting.cpp</p><p>// Interrupting a blocked thread.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include &lt;iostream&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class Blocked : public Runnable {</p><p>public:</p><p>  void run() {</p><p>    try {</p><p>      Thread::sleep(1000);</p><p>      cout &lt;&lt; "Waiting for get() in run():";</p><p>      cin.get();</p><p>    } catch(Interrupted_Exception&amp;) {</p><p>      cout &lt;&lt; "Caught Interrupted_Exception" &lt;&lt; endl;</p><p>      // Exit the task</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  try {</p><p>    Thread t(new Blocked);</p><p>    if(argc &gt; 1)</p><p>      Thread::sleep(1100);</p><p>    t.interrupt();</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>You can see that <strong>run( )</strong> contains <emphasis>two</emphasis> points where blocking can occur: the call to <strong>Thread::sleep(1000)</strong> and the call to <strong>cin.get( )</strong>. By giving the program any command-line argument, you tell <strong>main( )</strong> to sleep long enough that the task will finish its <strong>sleep( )</strong> and move into the <strong>cin.get( )</strong>. If you don’t give the program an argument, the <strong>sleep( )</strong> in <strong>main( )</strong> is skipped. In this case, the call to <strong>interrupt( )</strong> will occur while the task is sleeping, and you’ll see that this will cause <strong>Interrupted_Exception</strong> to be thrown. If you give the program a command-line argument, you’ll discover that a task cannot be interrupted if it is blocked on IO. That is, you can interrupt out of any blocking operation <emphasis>except</emphasis> IO.</p><p>This is a little disconcerting if you’re creating a thread that performs IO, because it means that I/O has the potential of locking your multithreaded program. The problem is that, again, C++ was not designed with threading in mind; quite the opposite, it effectively pretends that threading doesn’t exist. Thus, the iostream library is not thread-friendly. If the new C++ standard decides to add thread support, the iostream library may need to be reconsidered in the process.</p></section><section><section><title><p>Blocked by a mutex</p></title><p>In the previous list of ways to become blocked, the last one happens when you’re trying to call a function whose mutex has already been acquired. In this situation, the calling task will be suspended until the mutex becomes available. The following example tests whether this kind of blocking is interruptible:</p><p>//: C11:Interrupting2.cpp</p><p>// Interrupting a thread blocked</p><p>// with a synchronization guard.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/Mutex.h"</p><p>#include "zthread/Guard.h"</p><p>#include &lt;iostream&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class BlockedMutex {</p><p>  Mutex lock;</p><p>public:</p><p>  BlockedMutex() {</p><p>    lock.acquire();</p><p>  }</p><p>  void f() {</p><p>    Guard&lt;Mutex&gt; g(lock);</p><p>    // This will never be available</p><p>  }</p><p>};</p><empty-line/><p>class Blocked2 : public Runnable {</p><p>  BlockedMutex blocked;</p><p>public:</p><p>  void run() {</p><p>    try {</p><p>      cout &lt;&lt; "Waiting for f() in BlockedMutex" &lt;&lt; endl;</p><p>      blocked.f();</p><p>    } catch(Interrupted_Exception&amp; e) {</p><p>      cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>      // Exit the task</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  try {</p><p>    Thread t(new Blocked2);</p><p>    t.interrupt();</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>The class <strong>BlockedMutex</strong> has a constructor that acquires the object’s own <strong>Mutex</strong> and never releases it. For that reason, if you try to call <strong>f( )</strong>, you will always be blocked because the <strong>Mutex</strong> cannot be acquired. In <strong>Blocked2</strong>, the <strong>run( )</strong> function will therefore be stopped at the call to <strong>blocked.f( )</strong>. When you run the program you’ll see that, unlike the iostream call, <strong>interrupt( )</strong> can break out of a call that’s blocked by a mutex.</p></section><section><title><p>Checking for an interrupt</p></title><p>Note that when you call <strong>interrupt( ) </strong>on a thread, the only time that the interrupt occurs is when the task enters, or is already inside, a blocking operation (except, as you’ve seen, in the case of IO, where you’re just stuck). But what if you’ve written code that may or may not make such a blocking call, depending on the conditions in which it is run? If you can only exit by throwing an exception on a blocking call, you won’t always be able to leave the <strong>run( ) </strong>loop. Thus, if you call <strong>interrupt( )</strong> to stop a task, your task needs a <emphasis>second</emphasis> opportunity to exit in the event that your <strong>run( )</strong> loop doesn’t happen to be making any blocking calls.</p><p>This opportunity is presented by the <emphasis>interrupted status</emphasis>, which is set by the call to <strong>interrupt( )</strong>. You check for the interrupted status by calling <strong>interrupted( )</strong>. This not only tells you whether <strong>interrupt( )</strong> has been called, it also clears the interrupted status. Clearing the interrupted status ensures that the framework will not notify you twice about a task being interrupted. You will be notified via either a single <strong>Interrupted_Exception</strong>, or a single successful <strong>Thread::interrupted( )</strong> test. If you want to check again to see whether you were interrupted, you can store the result when you call <strong>Thread::interrupted( )</strong>.</p><p>The following example shows the typical idiom that you should use in your <strong>run( )</strong> function to handle both blocked and non-blocked possibilities when the interrupted status is set:</p><p>//: C11:Interrupting3.cpp</p><p>// General idiom for interrupting a task.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;cmath&gt;</p><p>#include &lt;cstdlib&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class NeedsCleanup {</p><p>  int id;</p><p>public:</p><p>  NeedsCleanup(int ident) : id(ident) {</p><p>    cout &lt;&lt; "NeedsCleanup " &lt;&lt; id &lt;&lt; endl;</p><p>  }</p><p>  ~NeedsCleanup() {</p><p>    cout &lt;&lt; "~NeedsCleanup " &lt;&lt; id &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class Blocked3 : public Runnable {</p><p>  volatile double d;</p><p>public:</p><p>  Blocked3() : d(0.0) {}</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        point1:</p><p>        NeedsCleanup n1(1);</p><p>        cout &lt;&lt; "Sleeping" &lt;&lt; endl;</p><p>        Thread::sleep(1000);</p><p>        point2:</p><p>        NeedsCleanup n2(2);</p><p>        cout &lt;&lt; "Calculating" &lt;&lt; endl;</p><p>        // A time-consuming, non-blocking operation:</p><p>        for(int i = 1; i &lt; 100000; i++)</p><p>          d = d + (M_PI + M_E) / (double)i;</p><p>      }</p><p>      cout &lt;&lt; "Exiting via while() test" &lt;&lt; endl;</p><p>    } catch(Interrupted_Exception&amp;) {</p><p>      cout &lt;&lt; "Exiting via Interrupted_Exception" &lt;&lt; endl;</p><p>    }</p><p>  }</p><p>};</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  if(argc != 2) {</p><p>    cerr &lt;&lt; "usage: " &lt;&lt; argv[0]</p><p>      &lt;&lt; " delay-in-milliseconds" &lt;&lt; endl;</p><p>    exit(1);</p><p>  }</p><p>  int delay = atoi(argv[1]);</p><p>  try {</p><p>    Thread t(new Blocked3);</p><p>    Thread::sleep(delay);</p><p>    t.interrupt();</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>The <strong>NeedsCleanup</strong> class emphasizes the necessity of proper resource cleanup if you leave the loop via an exception. Note that no pointers are defined in <strong>Blocked3::run( )</strong> because, for exception safety, all resources must be enclosed in stack-based objects so that the exception handler can automatically clean them up by calling the destructor.</p><p>You must give the program a command-line argument which is the delay time in milliseconds before it calls <strong>interrupt( )</strong>. By using different delays, you can exit <strong>Blocked3::run( )</strong> at different points in the loop: in the blocking <strong>sleep( )</strong> call, and in the non-blocking mathematical calculation. You’ll see that if <strong>interrupt( )</strong> is called after the label <strong>point2 </strong>(during the non-blocking operation), first the loop is completed, then all the local objects are destructed, and finally the loop is exited at the top via the <strong>while</strong> statement. However, if <strong>interrupt( )</strong> is called between <strong>point1 </strong>and <strong>point2 </strong>(after the <strong>while</strong> statement but before or during the blocking operation <strong>sleep( )</strong>), the task exits via the <strong>Interrupted_Exception</strong>. In that case, only the stack objects that have been created up to the point where the exception is thrown are cleaned up, and you have the opportunity to perform any other cleanup in the <strong>catch</strong> clause.</p><p>A class designed to respond to an <strong>interrupt( ) </strong>must establish a policy that ensures it will remain in a consistent state. This generally means that all resource acquisition should be wrapped inside stack-based objects so that the destructors will be called regardless of how the <strong>run( ) </strong>loop exits. Correctly done, code like this can be elegant. Components can be created that completely encapsulate their synchronization mechanisms but are still responsive to an external stimulus (via <strong>interrupt( )</strong>) without adding any special functions to an object’s interface.</p></section></section></section></section><section><title><p>Cooperation between threads</p></title><section><p>As you’ve seen, when you use threads to run more than one task at a time, you can keep one task from interfering with another task’s resources by using a mutex to synchronize the behavior of the two tasks. That is, if two tasks are stepping on each other over a shared resource (usually memory), you use a mutex to allow only one task at a time to access that resource.</p><p>With that problem solved, you can move on to the issue of getting threads to cooperate, so that multiple threads can work together to solve a problem. Now the issue is not about interfering with one another, but rather about working in unison, since portions of such problems must be solved before other portions can be solved. It’s much like project planning: the footings for the house must be dug first, but the steel can be laid and the concrete forms can be built in parallel, and both of those tasks must be finished before the concrete foundation can be poured. The plumbing must be in place before the concrete slab can be poured, the concrete slab must be in place before you start framing, and so on. Some of these tasks can be done in parallel, but certain steps require all tasks to be completed before you can move ahead.</p><p>The key issue when tasks are cooperating is handshaking between those tasks. To accomplish this handshaking, we use the same foundation: the mutex, which in this case guarantees that only one task can respond to a signal. This eliminates any possible race conditions. On top of the mutex, we add a way for a task to suspend itself until some external state changes ("the plumbing is now in place"), indicating that it’s time for that task to move forward. In this section, we’ll look at the issues of handshaking between tasks, the problems that can arise, and their solutions.</p></section><section><title><p>Wait and signal</p></title><p>In ZThreads, the basic class that uses a mutex and allows task suspension is the <strong>Condition</strong>, and you can suspend a task by calling <strong>wait( )</strong> on a <strong>Condition</strong>. When external state changes take place that might mean that a task should continue processing, you notify the task by calling <strong>signal( )</strong>, to wake up one task, or <strong>broadcast( )</strong>, to wake up all tasks that have suspended themselves on that <strong>Condition</strong> object.</p><p>There are two forms of <strong>wait( )</strong>. The first takes an argument in milliseconds that has the same meaning as in <strong>sleep( )</strong>: "pause for this period of time." The difference is that in a timed <strong>wait( )</strong>:</p><p>1.       The <strong>Mutex</strong> that is controlled by the <strong>Condition</strong> object is released during the <strong>wait( )</strong>.</p><p>2.      You can come out of the <strong>wait( )</strong> due to a <strong>signal( )</strong> or a <strong>broadcast( )</strong>, as well as by letting the clock run out.</p><p>The second form of <strong>wait( )</strong> takes no arguments; this version is more commonly used. It also releases the mutex, but this <strong>wait( )</strong> suspends the thread indefinitely until that <strong>Condition</strong> object receives a <strong>signal( )</strong> or <strong>broadcast( )</strong>.</p><p>Typically, you use <strong>wait( )</strong> when you’re waiting for some condition to change that is under the control of forces outside the current function. (Often, this condition will be changed by another thread.) You don’t want to idly loop while testing the condition inside your thread; this is called a "busy wait," and it’s a bad use of CPU cycles. Thus, <strong>wait( )</strong> allows you to suspend the thread while waiting for the world to change, and only when a <strong>signal( )</strong> or <strong>broadcast( ) </strong>occurs (suggesting that something of interest may have happened), does the thread wake up and check for changes. Therefore, <strong>wait( )</strong> provides a way to synchronize activities between threads.</p><p>Let’s look at a simple example. <strong>WaxOMatic.cpp</strong> applies wax to a <strong>Car </strong>and polishes it using two separate processes. The polishing process cannot do its job until the application process is finished, and the application process must wait until the polishing process is finished before it can put on another coat of wax. Both <strong>WaxOn</strong> and <strong>WaxOff</strong> use the <strong>Car</strong> object, which contains a <strong>Condition</strong> that it uses to suspend a thread inside <strong>waitForWaxing( )</strong> or <strong>waitForBuffing( )</strong>:</p><p>//: C11:WaxOMatic.cpp</p><p>// Basic thread cooperation.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/Mutex.h"</p><p>#include "zthread/Guard.h"</p><p>#include "zthread/Condition.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class Car {</p><p>  Mutex lock;</p><p>  Condition condition;</p><p>  bool waxOn;</p><p>public:</p><p>  Car() : condition(lock), waxOn(false) {}</p><p>  void waxed() {</p><p>    Guard&lt;Mutex&gt; g(lock);</p><p>    waxOn = true; // Ready to buff</p><p>    condition.signal();</p><p>  }</p><p>  void buffed() {</p><p>    Guard&lt;Mutex&gt; g(lock);</p><p>    waxOn = false; // Ready for another coat of wax</p><p>    condition.signal();</p><p>  }</p><p>  void waitForWaxing() {</p><p>    Guard&lt;Mutex&gt; g(lock);</p><p>    while(waxOn == false)</p><p>      condition.wait();</p><p>  }</p><p>  void waitForBuffing() {</p><p>    Guard&lt;Mutex&gt; g(lock);</p><p>    while(waxOn == true)</p><p>      condition.wait();</p><p>  }</p><p>};</p><empty-line/><p>class WaxOn : public Runnable {</p><p>  CountedPtr&lt;Car&gt; car;</p><p>public:</p><p>  WaxOn(CountedPtr&lt;Car&gt;&amp; c) : car(c) {}</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        cout &lt;&lt; "Wax On!" &lt;&lt; endl;</p><p>        Thread::sleep(200);</p><p>        car-&gt;waxed();</p><p>        car-&gt;waitForBuffing();</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "Ending Wax On process" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class WaxOff : public Runnable {</p><p>  CountedPtr&lt;Car&gt; car;</p><p>public:</p><p>  WaxOff(CountedPtr&lt;Car&gt;&amp; c) : car(c) {}</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        car-&gt;waitForWaxing();</p><p>        cout &lt;&lt; "Wax Off!" &lt;&lt; endl;</p><p>        Thread::sleep(200);</p><p>        car-&gt;buffed();</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "Ending Wax Off process" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  cout &lt;&lt; "Press &lt;Enter&gt; to quit" &lt;&lt; endl;</p><p>  try {</p><p>    CountedPtr&lt;Car&gt; car(new Car);</p><p>    ThreadedExecutor executor;</p><p>    executor.execute(new WaxOff(car));</p><p>    executor.execute(new WaxOn(car));</p><p>    cin.get();</p><p>    executor.interrupt();</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>In <strong>Car</strong>’s constructor, a single <strong>Mutex</strong> is wrapped in a <strong>Condition</strong> object so that it can be used to manage inter-task communication. However, the <strong>Condition</strong> object contains no information about the state of your process, so you need to manage additional information to indicate process state. Here, <strong>Car</strong> has a single <strong>bool waxOn</strong>, which indicates the state of the waxing-polishing process.</p><p>In <strong>waitForWaxing( )</strong>, the <strong>waxOn</strong> flag is checked, and if it is <strong>false</strong>, the calling thread is suspended by calling <strong>wait( )</strong> on the <strong>Condition</strong> object. It’s important that this occur inside a guarded clause, in which the thread has acquired the lock (here, by creating a <strong>Guard</strong> object). When you call <strong>wait( )</strong>, the thread is suspended and <emphasis>the lock is released</emphasis>. It is essential that the lock be released because, to safely change the state of the object (for example, to change <strong>waxOn</strong> to <strong>true</strong>, which must happen if the suspended thread is to ever continue), that lock must be available to be acquired by some other task. In this example, when another thread calls <strong>waxed( )</strong> to tell it that it’s time to do something, the mutex must be acquired in order to change <strong>waxOn</strong> to <strong>true</strong>. Afterward, <strong>waxed( ) </strong>sends a <strong>signal( )</strong> to the <strong>Condition</strong> object, which wakes up the thread suspended in the call to <strong>wait( )</strong>. Although <strong>signal( )</strong> may be called inside a guarded clause—as it is here—you are not required to do this.<a l:href="#n127" type="note">[127]</a></p><p>In order for a thread to wake up from a <strong>wait( )</strong>, it must first reacquire the mutex that it released when it entered the <strong>wait( )</strong>. The thread will not wake up until that mutex becomes available.</p><p>The call to <strong>wait( )</strong> is placed inside a <strong>while</strong> loop that checks the condition of interest. This is important for two reasons:</p><p>·         It is possible that when the thread gets a <strong>signal( )</strong>, some other condition has changed that is not associated with the reason that we called <strong>wait( )</strong> here. If that is the case, this thread should be suspended again until its condition of interest changes.</p><p>·         By the time this thread awakens from its <strong>wait( )</strong>, it’s possible that some other task has changed things such that this thread is unable or uninterested in performing its operation at this time. Again, it should be re-suspended by calling <strong>wait( )</strong> again.</p><p>Because these two reasons are always present when you are calling <strong>wait( )</strong>, always write your call to <strong>wait( )</strong> inside a <strong>while</strong> loop that tests for your condition(s) of interest.</p><p><strong>WaxOn::run( )</strong> represents the first step in the process of waxing the car, so it performs its operation (a call to <strong>sleep( )</strong> to simulate the time necessary for waxing). It then tells the car that waxing is complete, and calls <strong>waitForBuffing( )</strong>, which suspends this thread with a <strong>wait( ) </strong>until the <strong>WaxOff</strong> process calls <strong>buffed( )</strong> for the car, changing the state and calling <strong>notify( )</strong>. <strong>WaxOff::run( )</strong>, on the other hand, immediately moves into <strong>waitForWaxing( )</strong> and is thus suspended until the wax has been applied by <strong>WaxOn</strong> and <strong>waxed( )</strong> is called. When you run this program, you can watch this two-step process repeat itself as control is handed back and forth between the two threads. When you press the &lt;Enter&gt; key, <strong>interrupt( )</strong> halts both threads—when you call <strong>interrupt( )</strong> for an <strong>Executor</strong>, it calls <strong>interrupt( )</strong> for all the threads it is controlling.</p></section><section><title><p>Producer-consumer relationships</p></title><p>A common situation in threading problems is the <emphasis>producer-consumer</emphasis> relationship, in which one task is creating objects and other tasks are consuming them. In such a situation, make sure that (among other things) the consuming tasks do not accidentally skip any of the produced objects.</p><p>To show this problem, consider a machine that has three tasks: one to make toast, one to butter the toast, and one to put jam on the buttered toast.</p><p>//: C11:ToastOMatic.cpp</p><p>// Problems with thread cooperation.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/Mutex.h"</p><p>#include "zthread/Guard.h"</p><p>#include "zthread/Condition.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>// Apply jam to buttered toast:</p><p>class Jammer : public Runnable {</p><p>  Mutex lock;</p><p>  Condition butteredToastReady;</p><p>  bool gotButteredToast;</p><p>  int jammed;</p><p>public:</p><p>  Jammer(): butteredToastReady(lock) {</p><p>    gotButteredToast = false;</p><p>    jammed = 0;</p><p>  }</p><p>  void moreButteredToastReady() {</p><p>    Guard&lt;Mutex&gt; g(lock);</p><p>    gotButteredToast = true;</p><p>    butteredToastReady.signal();</p><p>  }</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        {</p><p>          Guard&lt;Mutex&gt; g(lock);</p><p>          while(!gotButteredToast)</p><p>            butteredToastReady.wait();</p><p>          jammed++;</p><p>        }</p><p>        cout &lt;&lt; "Putting jam on toast " &lt;&lt; jammed &lt;&lt; endl;</p><p>        {</p><p>          Guard&lt;Mutex&gt; g(lock);</p><p>          gotButteredToast = false;</p><p>        }</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "Jammer off" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>// Apply butter to toast:</p><p>class Butterer : public Runnable {</p><p>  Mutex lock;</p><p>  Condition toastReady;</p><p>  CountedPtr&lt;Jammer&gt; jammer;</p><p>  bool gotToast;</p><p>  int buttered;</p><p>public:</p><p>  Butterer(CountedPtr&lt;Jammer&gt;&amp; j)</p><p>  : jammer(j), toastReady(lock) {</p><p>    gotToast = false;</p><p>    buttered = 0;</p><p>  }</p><p>  void moreToastReady() {</p><p>    Guard&lt;Mutex&gt; g(lock);</p><p>    gotToast = true;</p><p>    toastReady.signal();</p><p>  }</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        {</p><p>          Guard&lt;Mutex&gt; g(lock);</p><p>          while(!gotToast)</p><p>            toastReady.wait();</p><p>          buttered++;</p><p>        }</p><p>        cout &lt;&lt; "Buttering toast " &lt;&lt; buttered &lt;&lt; endl;</p><p>        jammer-&gt;moreButteredToastReady();</p><p>        {</p><p>          Guard&lt;Mutex&gt; g(lock);</p><p>          gotToast = false;</p><p>        }</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "Butterer off" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class Toaster : public Runnable {</p><p>  CountedPtr&lt;Butterer&gt; butterer;</p><p>  int toasted;</p><p>public:</p><p>  Toaster(CountedPtr&lt;Butterer&gt;&amp; b) : butterer(b) {</p><p>    toasted = 0;</p><p>    srand(time(0)); // Seed the random number generator</p><p>  }</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        Thread::sleep(rand()/(RAND_MAX/5)*100);</p><p>        // ...</p><p>        // Create new toast</p><p>        // ...</p><p>        cout &lt;&lt; "New toast " &lt;&lt; ++toasted &lt;&lt; endl;</p><p>        butterer-&gt;moreToastReady();</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "Toaster off" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  try {</p><p>    cout &lt;&lt; "Press &lt;Return&gt; to quit" &lt;&lt; endl;</p><p>    CountedPtr&lt;Jammer&gt; jammer(new Jammer);</p><p>    CountedPtr&lt;Butterer&gt; butterer(new Butterer(jammer));</p><p>    ThreadedExecutor executor;</p><p>    executor.execute(new Toaster(butterer));</p><p>    executor.execute(butterer);</p><p>    executor.execute(jammer);</p><p>    cin.get();</p><p>    executor.interrupt();</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>The classes are defined in the reverse order that they operate to simplify forward-referencing issues.</p><p><strong>Jammer</strong> and <strong>Butterer</strong> both contain a <strong>Mutex</strong>, a <strong>Condition</strong>, and some kind of internal state information that changes to indicate that the process should suspend or resume. (<strong>Toaster</strong> doesn’t need these since it is the producer and doesn’t have to wait on anything.) The two <strong>run( )</strong> functions perform an operation, set a state flag, and then call <strong>wait( )</strong> to suspend the task. The <strong>moreToastReady( )</strong> and <strong>moreButteredToastReady( )</strong> functions change their respective state flags to indicate that something has changed and the process should consider resuming and then call <strong>signal( )</strong> to wake up the thread.</p><p>The difference between this example and the previous one is that, at least conceptually, something is being produced here: toast. The rate of toast production is randomized a bit, to add some uncertainty. And you’ll see that when you run the program, things aren’t going right, because many pieces of toast appear to be getting dropped on the floor—not buttered, not jammed.</p></section><section><title><p>Solving threading problems with queues</p></title><section><p>Often, threading problems are based on the need for tasks to be serialized—that is, to take care of things in order. <strong>ToastOMatic.cpp</strong> must not only take care of things in order, it must be able to work on one piece of toast without worrying that toast is falling on the floor in the meantime. You can solve many threading problems by using a queue that synchronizes access to the elements within:</p><p>//: C11:TQueue.h</p><p>#ifndef TQUEUE_H</p><p>#define TQUEUE_H</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/Condition.h"</p><p>#include "zthread/Mutex.h"</p><p>#include "zthread/Guard.h"</p><p>#include &lt;deque&gt;</p><empty-line/><p>template&lt;class T&gt; class TQueue {</p><p>  ZThread::Mutex lock;</p><p>  ZThread::Condition cond;</p><p>  std::deque&lt;T&gt; data;</p><p>public:</p><p>  TQueue() : cond(lock) {}</p><p>  void put(T item) {</p><p>    ZThread::Guard&lt;ZThread::Mutex&gt; g(lock);</p><p>    data.push_back(item);</p><p>    cond.signal();</p><p>  }</p><p>  T get() {</p><p>    ZThread::Guard&lt;ZThread::Mutex&gt; g(lock);</p><p>    while(data.empty())</p><p>      cond.wait();</p><p>    T returnVal = data.front();</p><p>    data.pop_front();</p><p>    return returnVal;</p><p>  }</p><p>};</p><p>#endif // TQUEUE_H ///:~</p><empty-line/><p>This builds on the Standard C++ Library <strong>deque</strong> by adding:</p><p>1.Synchronization to ensure that no two threads add objects at the same time.</p><p>2.<strong>wait( )</strong> and <strong>signal( )</strong> so that a consumer thread will automatically suspend if the queue is empty, and resume when more elements become available. </p><p>This relatively small amount of code can solve a remarkable number of problems.</p><p>Here’s a simple test that serializes the execution of <strong>LiftOff</strong> objects. The consumer is <strong>LiftOffRunner</strong>, which pulls each <strong>LiftOff</strong> object off the <strong>TQueue</strong> and runs it directly. (That is, it uses its own thread by calling <strong>run( )</strong> explicitly rather than starting up a new thread for each task.)</p><p>//: C11:TestTQueue.cpp</p><p>//{L} ZThread</p><p>#include &lt;string&gt;</p><p>#include &lt;iostream&gt;</p><p>#include "TQueue.h"</p><p>#include "zthread/Thread.h"</p><p>#include "LiftOff.h"</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class LiftOffRunner : public Runnable {</p><p>  TQueue&lt;LiftOff*&gt; rockets;</p><p>public:</p><p>  void add(LiftOff* lo) { rockets.put(lo); }</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        LiftOff* rocket = rockets.get();</p><p>        rocket-&gt;run();</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "Exiting LiftOffRunner" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  try {</p><p>    LiftOffRunner* lor = new LiftOffRunner;</p><p>    Thread t(lor);</p><p>    for(int i = 0; i &lt; 5; i++)</p><p>      lor-&gt;add(new LiftOff(10, i));</p><p>    cin.get();</p><p>    lor-&gt;add(new LiftOff(10, 99));</p><p>    cin.get();</p><p>    t.interrupt();</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>The tasks are placed on the <strong>TQueue</strong> by <strong>main( )</strong> and are taken off the <strong>TQueue</strong> by the <strong>LiftOffRunner</strong>. Notice that <strong>LiftOffRunner</strong> can ignore the synchronization issues because they are solved by the <strong>TQueue</strong>.</p></section><section><section><title><p>Proper toasting</p></title><p>To solve the <strong>ToastOMatic.cpp</strong> problem, we can run the toast through <strong>TQueue</strong>s between processes. And to do this, we will need actual toast objects, which maintain and display their state:</p><p>//: C11:ToastOMaticMarkII.cpp</p><p>// Solving the problems using TQueues</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/Mutex.h"</p><p>#include "zthread/Guard.h"</p><p>#include "zthread/Condition.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include "TQueue.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;ctime&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class Toast {</p><p>  enum Status { dry, buttered, jammed };</p><p>  Status status;</p><p>  int id;</p><p>public:</p><p>  Toast(int idn) : id(idn), status(dry) {}</p><p>  void butter() { status = buttered; }</p><p>  void jam() { status = jammed; }</p><p>  string getStatus() const {</p><p>    switch(status) {</p><p>      case dry: return "dry";</p><p>      case buttered: return "buttered";</p><p>      case jammed: return "jammed";</p><p>      default: return "error";</p><p>    }</p><p>  }</p><p>  int getId() { return id; }</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Toast&amp; t) {</p><p>    return os &lt;&lt; "Toast " &lt;&lt; t.id &lt;&lt; ": " &lt;&lt; t.getStatus();</p><p>  }</p><p>};</p><empty-line/><p>typedef CountedPtr&lt; TQueue&lt;Toast&gt; &gt; ToastQueue;</p><empty-line/><p>class Toaster : public Runnable {</p><p>  ToastQueue toastQueue;</p><p>  int count;</p><p>public:</p><p>  Toaster(ToastQueue&amp; tq) : toastQueue(tq), count(0) {</p><p>    srand(time(0)); // Seed the random number generator</p><p>  }</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        int delay = rand()/(RAND_MAX/5)*100;</p><p>        Thread::sleep(delay);</p><p>        // Make toast</p><p>        Toast t(count++);</p><p>        cout &lt;&lt; t &lt;&lt; endl;</p><p>        // Insert into queue</p><p>        toastQueue-&gt;put(t);</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "Toaster off" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>// Apply butter to toast:</p><p>class Butterer : public Runnable {</p><p>  ToastQueue dryQueue, butteredQueue;</p><p>public:</p><p>  Butterer(ToastQueue&amp; dry, ToastQueue&amp; buttered)</p><p>  : dryQueue(dry), butteredQueue(buttered) {}</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        // Blocks until next piece of toast is available:</p><p>        Toast t = dryQueue-&gt;get();</p><p>        t.butter();</p><p>        cout &lt;&lt; t &lt;&lt; endl;</p><p>        butteredQueue-&gt;put(t);</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "Butterer off" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>// Apply jam to buttered toast:</p><p>class Jammer : public Runnable {</p><p>  ToastQueue butteredQueue, finishedQueue;</p><p>public:</p><p>  Jammer(ToastQueue&amp; buttered, ToastQueue&amp; finished) </p><p>  : butteredQueue(buttered), finishedQueue(finished) {}</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        // Blocks until next piece of toast is available:</p><p>        Toast t = butteredQueue-&gt;get();</p><p>        t.jam();</p><p>        cout &lt;&lt; t &lt;&lt; endl;</p><p>        finishedQueue-&gt;put(t);</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "Jammer off" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>// Consume the toast:</p><p>class Eater : public Runnable {</p><p>  ToastQueue finishedQueue;</p><p>  int counter;</p><p>public:</p><p>  Eater(ToastQueue&amp; finished) </p><p>  : finishedQueue(finished), counter(0) {}</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        // Blocks until next piece of toast is available:</p><p>        Toast t = finishedQueue-&gt;get();</p><p>        // Verify that the toast is coming in order,</p><p>        // and that all pieces are getting jammed:</p><p>        if(t.getId() != counter++ || </p><p>           t.getStatus() != "jammed") {</p><p>          cout &lt;&lt; "&gt;&gt;&gt;&gt; Error: " &lt;&lt; t &lt;&lt; endl;</p><p>          exit(1);</p><p>        } else</p><p>          cout &lt;&lt; "Chomp! " &lt;&lt; t &lt;&lt; endl;</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "Eater off" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  try {</p><p>    ToastQueue dryQueue(new TQueue&lt;Toast&gt;),</p><p>butteredQueue(new TQueue&lt;Toast&gt;),</p><p>finishedQueue(new TQueue&lt;Toast&gt;);</p><p>    cout &lt;&lt; "Press &lt;Return&gt; to quit" &lt;&lt; endl;</p><p>    ThreadedExecutor executor;</p><p>    executor.execute(new Toaster(dryQueue));</p><p>    executor.execute(new Butterer(dryQueue,butteredQueue));</p><p>    executor.execute(</p><p>      new Jammer(butteredQueue, finishedQueue));</p><p>    executor.execute(new Eater(finishedQueue));</p><p>    cin.get();</p><p>    executor.interrupt();</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>Two things are immediately apparent in this solution: first, the amount and complexity of code within each <strong>Runnable</strong> class is dramatically reduced by the use of the <strong>TQueue</strong>, because the guarding, communication, and <strong>wait( )/signal( )</strong> operations are now taken care of by the <strong>TQueue</strong>. The <strong>Runnable</strong> classes don’t have <strong>Mutex</strong>es or <strong>Condition</strong> objects anymore. Second, the coupling between the classes is eliminated because each class communicates only with its <strong>TQueue</strong>s. Notice that the definition order of the classes is now independent. Less code and less coupling is always a good thing, which suggests that the use of the <strong>TQueue</strong> has a positive effect here, as it does on most problems.</p></section></section></section><section><title><p>Broadcast</p></title><p>The <strong>signal( )</strong> function wakes up a single thread that is waiting on a <strong>Condition</strong> object. However, multiple threads may be waiting on the same condition object, and in that case you’ll want to wake them all up using <strong>broadcast( )</strong> instead of <strong>signal( )</strong>.</p><p>As an example that brings together many of the concepts in this chapter, consider a hypothetical robotic assembly line for automobiles. Each <strong>Car</strong> will be built in several stages, and in this example we’ll look at a single stage: after the chassis has been created, at the time when the engine, drive train, and wheels are attached. The <strong>Car</strong>s are transported from one place to another via a <strong>CarQueue</strong>, which is a type of <strong>TQueue</strong>. A <strong>Director</strong> takes each <strong>Car</strong> (as a raw chassis) from the incoming <strong>CarQueue</strong> and places it in a <strong>Cradle</strong>, which is where all the work is done. At this point, the <strong>Director</strong> tells all the waiting robots (using <strong>broadcast( )</strong>) that the <strong>Car</strong> is in the <strong>Cradle</strong> ready for the robots to work on it. The three types of robots go to work, sending a message to the <strong>Cradle</strong> when they finish their tasks. The <strong>Director</strong> waits until all the tasks are complete and then puts the <strong>Car</strong> onto the outgoing <strong>CarQueue</strong> to be transported to the next operation. In this case, the consumer of the outgoing <strong>CarQueue</strong> is a <strong>Reporter</strong> object, which just prints the <strong>Car</strong> to show that the tasks have been properly completed.</p><p>//: C11:CarBuilder.cpp</p><p>// How broadcast() works.</p><p>//{L} ZThread</p><p>#include "zthread/Thread.h"</p><p>#include "zthread/Mutex.h"</p><p>#include "zthread/Guard.h"</p><p>#include "zthread/Condition.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include "TQueue.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;string&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>class Car {</p><p>  bool engine, driveTrain, wheels;</p><p>  int id;</p><p>public:</p><p>  Car(int idn) : id(idn), engine(false),</p><p>  driveTrain(false), wheels(false) {}</p><p>  // Empty Car object:</p><p>  Car() : id(-1), engine(false),</p><p>  driveTrain(false), wheels(false) {}</p><p>  // Unsynchronized -- assumes atomic bool operations:</p><p>  int getId() { return id; }</p><p>  void addEngine() { engine = true; }</p><p>  bool engineInstalled() { return engine; }</p><p>  void addDriveTrain() { driveTrain = true; }</p><p>  bool driveTrainInstalled() { return driveTrain; }</p><p>  void addWheels() { wheels = true; }</p><p>  bool wheelsInstalled() { return wheels; }</p><p>  friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Car&amp; c) {</p><p>    return os &lt;&lt; "Car " &lt;&lt; c.id &lt;&lt; " ["</p><p>      &lt;&lt; " engine: " &lt;&lt; c.engine</p><p>      &lt;&lt; " driveTrain: " &lt;&lt; c.driveTrain</p><p>      &lt;&lt; " wheels: " &lt;&lt; c.wheels &lt;&lt; " ]";</p><p>  }</p><p>};</p><empty-line/><p>typedef CountedPtr&lt; TQueue&lt;Car&gt; &gt; CarQueue;</p><empty-line/><p>class ChassisBuilder : public Runnable {</p><p>  CarQueue carQueue;</p><p>  int counter;</p><p>public:</p><p>  ChassisBuilder(CarQueue&amp; cq) : carQueue(cq), counter(0){}</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        Thread::sleep(1000);</p><p>        // Make chassis:</p><p>        Car c(counter++);</p><p>        cout &lt;&lt; c &lt;&lt; endl;</p><p>        // Insert into queue</p><p>        carQueue-&gt;put(c);</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "ChassisBuilder off" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class Cradle {</p><p>  Car c; // Holds current car being worked on</p><p>  bool occupied;</p><p>  Mutex workLock, readyLock;</p><p>  Condition workCondition, readyCondition;</p><p>  bool engineBotHired, wheelBotHired, driveTrainBotHired;</p><p>public:</p><p>  Cradle()</p><p>  : workCondition(workLock), readyCondition(readyLock) {</p><p>    occupied = false;</p><p>    engineBotHired = true;</p><p>    wheelBotHired = true;</p><p>    driveTrainBotHired = true;</p><p>  }</p><p>  void insertCar(Car chassis) {</p><p>    c = chassis;</p><p>    occupied = true;</p><p>  }</p><p>  Car getCar() { // Can only extract car once</p><p>    if(!occupied) {</p><p>      cerr &lt;&lt; "No Car in Cradle for getCar()" &lt;&lt; endl;</p><p>      return Car(); // "Null" Car object</p><p>    }</p><p>    occupied = false;</p><p>    return c;</p><p>  }</p><p>  // Access car while in cradle:</p><p>  Car* operator-&gt;() { return &amp;c; }</p><p>  // Allow robots to offer services to this cradle:</p><p>  void offerEngineBotServices() {</p><p>    Guard&lt;Mutex&gt; g(workLock);</p><p>    while(engineBotHired)</p><p>      workCondition.wait();</p><p>    engineBotHired = true; // Accept the job</p><p>  }</p><p>  void offerWheelBotServices() {</p><p>    Guard&lt;Mutex&gt; g(workLock);</p><p>    while(wheelBotHired)</p><p>      workCondition.wait();</p><p>    wheelBotHired = true; // Accept the job</p><p>  }</p><p>  void offerDriveTrainBotServices() {</p><p>    Guard&lt;Mutex&gt; g(workLock);</p><p>    while(driveTrainBotHired)</p><p>      workCondition.wait();</p><p>    driveTrainBotHired = true; // Accept the job</p><p>  }</p><p>  // Tell waiting robots that work is ready:</p><p>  void startWork() {</p><p>    Guard&lt;Mutex&gt; g(workLock);</p><p>    engineBotHired = false;</p><p>    wheelBotHired = false;</p><p>    driveTrainBotHired = false;</p><p>    workCondition.broadcast();</p><p>  }</p><p>  // Each robot reports when their job is done:</p><p>  void taskFinished() {</p><p>    Guard&lt;Mutex&gt; g(readyLock);</p><p>    readyCondition.signal();</p><p>  }</p><p>  // Director waits until all jobs are done:</p><p>  void waitUntilWorkFinished() {</p><p>    Guard&lt;Mutex&gt; g(readyLock);</p><p>    while(!(c.engineInstalled() &amp;&amp; c.driveTrainInstalled()</p><p>            &amp;&amp; c.wheelsInstalled()))</p><p>      readyCondition.wait();</p><p>  }</p><p>};</p><empty-line/><p>typedef CountedPtr&lt;Cradle&gt; CradlePtr;</p><empty-line/><p>class Director : public Runnable {</p><p>  CarQueue chassisQueue, finishingQueue;</p><p>  CradlePtr cradle;</p><p>public:</p><p>  Director(CarQueue&amp; cq, CarQueue&amp; fq, CradlePtr cr)</p><p>  : chassisQueue(cq), finishingQueue(fq), cradle(cr) {}</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        // Blocks until chassis is available:</p><p>        cradle-&gt;insertCar(chassisQueue-&gt;get());</p><p>        // Notify robots car is ready for work</p><p>        cradle-&gt;startWork();</p><p>        // Wait until work completes</p><p>        cradle-&gt;waitUntilWorkFinished();</p><p>        // Put car into queue for further work</p><p>        finishingQueue-&gt;put(cradle-&gt;getCar());</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "Director off" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class EngineRobot : public Runnable {</p><p>  CradlePtr cradle;</p><p>public:</p><p>  EngineRobot(CradlePtr cr) : cradle(cr) {}</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        // Blocks until job is offered/accepted:</p><p>        cradle-&gt;offerEngineBotServices();</p><p>        cout &lt;&lt; "Installing engine" &lt;&lt; endl;</p><p>        (*cradle)-&gt;addEngine();</p><p>        cradle-&gt;taskFinished();</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "EngineRobot off" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class DriveTrainRobot : public Runnable {</p><p>  CradlePtr cradle;</p><p>public:</p><p>  DriveTrainRobot(CradlePtr cr) : cradle(cr) {}</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        // Blocks until job is offered/accepted:</p><p>        cradle-&gt;offerDriveTrainBotServices();</p><p>        cout &lt;&lt; "Installing DriveTrain" &lt;&lt; endl;</p><p>        (*cradle)-&gt;addDriveTrain();</p><p>        cradle-&gt;taskFinished();</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "DriveTrainRobot off" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class WheelRobot : public Runnable {</p><p>  CradlePtr cradle;</p><p>public:</p><p>  WheelRobot(CradlePtr cr) : cradle(cr) {}</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        // Blocks until job is offered/accepted:</p><p>        cradle-&gt;offerWheelBotServices();</p><p>        cout &lt;&lt; "Installing Wheels" &lt;&lt; endl;</p><p>        (*cradle)-&gt;addWheels();</p><p>        cradle-&gt;taskFinished();</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "WheelRobot off" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>class Reporter : public Runnable {</p><p>  CarQueue carQueue;</p><p>public:</p><p>  Reporter(CarQueue&amp; cq) : carQueue(cq) {}</p><p>  void run() {</p><p>    try {</p><p>      while(!Thread::interrupted()) {</p><p>        cout &lt;&lt; carQueue-&gt;get() &lt;&lt; endl;</p><p>      }</p><p>    } catch(Interrupted_Exception&amp;) { /* Exit */ }</p><p>    cout &lt;&lt; "Reporter off" &lt;&lt; endl;</p><p>  }</p><p>};</p><empty-line/><p>int main() {</p><p>  cout &lt;&lt; "Press &lt;Enter&gt; to quit" &lt;&lt; endl;</p><p>  try {</p><p>    CarQueue chassisQueue(new TQueue&lt;Car&gt;),</p><p>             finishingQueue(new TQueue&lt;Car&gt;);</p><p>    CradlePtr cradle(new Cradle);</p><p>    ThreadedExecutor assemblyLine;</p><p>    assemblyLine.execute(new EngineRobot(cradle));</p><p>    assemblyLine.execute(new DriveTrainRobot(cradle));</p><p>    assemblyLine.execute(new WheelRobot(cradle));</p><p>    assemblyLine.execute(</p><p>      new Director(chassisQueue, finishingQueue, cradle));</p><p>    assemblyLine.execute(new Reporter(finishingQueue));</p><p>    // Start everything running by producing chassis:</p><p>    assemblyLine.execute(new ChassisBuilder(chassisQueue));</p><p>    cin.get();</p><p>    assemblyLine.interrupt();</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>You’ll notice that <strong>Car </strong>takes a shortcut: it assumes that <strong>bool</strong> operations are atomic, which, as previously discussed, is generally a safe assumption but one to consider carefully. Each <strong>Car</strong> begins as an unadorned chassis, and different robots will attach different parts to it, calling the appropriate "add" function when they do.</p><p>A <strong>ChassisBuilder</strong> simply creates a new <strong>Car</strong> every second and places it into the <strong>chassisQueue</strong>. A <strong>Director</strong> manages the build process by taking the next <strong>Car</strong> off the <strong>chassisQueue</strong>, putting it into the <strong>Cradle</strong>, telling all the robots to <strong>startWork( )</strong>, and suspending itself by calling <strong>waitUntilWorkFinished( )</strong>. When the work is done, the <strong>Director</strong> takes the <strong>Car</strong> out of the <strong>Cradle</strong> and puts in into the <strong>finishingQueue</strong>.</p><p>The <strong>Cradle</strong> is the crux of the signaling operations. A <strong>Mutex</strong> and a <strong>Condition</strong> object control both the working of the robots and indicate whether all the operations are finished. A particular type of robot can offer its services to the <strong>Cradle</strong> by calling the "offer" function appropriate to its type. At this point, that robot thread is suspended until the <strong>Director</strong> calls <strong>startWork( )</strong>, which changes the hiring flags and calls <strong>broadcast( )</strong> to tell all the robots to show up for work. Although this system allows any number of robots to offer their services, each one of those robots has its thread suspended by doing so. You could imagine a more sophisticated system in which the robots register themselves with many different <strong>Cradle</strong>s without being suspended by that registration process and then reside in a pool waiting for the first <strong>Cradle</strong> that needs a task completed.</p><p>After each robot finishes its task (changing the state of the <strong>Car</strong> in the process), it calls <strong>taskFinished( )</strong>, which sends a <strong>signal( )</strong> to the <strong>readyCondition</strong>, which is what the <strong>Director</strong> is waiting on in <strong>waitUntilWorkFinished( )</strong>. Each time the director thread awakens, the state of the <strong>Car</strong> is checked, and if it still isn’t finished, that thread is suspended again.</p><p>When the <strong>Director </strong>inserts a <strong>Car</strong> into the <strong>Cradle</strong>, you can perform operations on that <strong>Car</strong> via the <strong>operator-&gt;( )</strong>. To prevent multiple extractions of the same car, a flag causes an error report to be generated. (Exceptions don’t propagate across threads in the ZThread library.)</p><p>In <strong>main( )</strong>, all the necessary objects are created and the tasks are initialized, with the <strong>ChassisBuilder</strong> begun last to start the process. (However, because of the behavior of the <strong>TQueue</strong>, it wouldn’t matter if it were started first.) Note that this program follows all the guidelines regarding object and task lifetime presented in this chapter, and so the shutdown process is safe.</p></section></section><section><title><p>Deadlock</p></title><p>Because threads can become blocked <emphasis>and</emphasis> because objects can have mutexes that prevent threads from accessing that object until the mutex is released, it’s possible for one thread to get stuck waiting for another thread, which in turn waits for another thread, and so on, until the chain leads back to a thread waiting on the first one. You get a continuous loop of threads waiting on each other, and no one can move. This is called <emphasis>deadlock</emphasis>.</p><p>If you try running a program and it deadlocks right away, you immediately know you have a problem, and you can track it down. The real problem is when your program seems to be working fine but has the hidden potential to deadlock. In this case, you may get no indication that deadlocking is a possibility, so it will be latent in your program until it unexpectedly happens to a customer. (And you probably won’t be able to easily reproduce it.) Thus, preventing deadlock through careful program design is a critical part of developing concurrent programs.</p><p>Let’s look at the classic demonstration of deadlock, invented by Edsger Dijkstra: the <emphasis>dining philosophers</emphasis> problem. The basic description specifies five philosophers (but the example shown here will allow any number). These philosophers spend part of their time thinking and part of their time eating. While they are thinking, they don’t need any shared resources, but when they are eating, they sit at a table with a limited number of utensils. In the original problem description, the utensils are forks, and two forks are required to get spaghetti from a bowl in the middle of the table, but it seems to make more sense to say that the utensils are chopsticks. Clearly, each philosopher will require two chopsticks in order to eat.</p><p>A difficulty is introduced into the problem: as philosophers, they have very little money, so they can only afford five chopsticks. These are spaced around the table between them. When a philosopher wants to eat, they must pick up the chopstick to the left and the one to the right. If the philosopher on either side is using a desired chopstick, our philosopher must wait until the necessary chopsticks become available. </p><p>//: C11:DiningPhilosophers.h</p><p>// Classes for Dining Philosohophers</p><p>#ifndef DININGPHILOSOPHERS_H</p><p>#define DININGPHILOSOPHERS_H</p><p>#include "zthread/Condition.h"</p><p>#include "zthread/Guard.h"</p><p>#include "zthread/Mutex.h"</p><p>#include "zthread/Thread.h"</p><p>#include "Display.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;cstdlib&gt;</p><empty-line/><p>class Chopstick {</p><p>  ZThread::Mutex lock;</p><p>  ZThread::Condition notTaken;</p><p>  bool taken;</p><p>public:</p><p>  Chopstick() : notTaken(lock), taken(false) {}</p><p>  void take() {</p><p>    ZThread::Guard&lt;ZThread::Mutex&gt; g(lock);</p><p>    while(taken)</p><p>      notTaken.wait();</p><p>    taken = true;</p><p>  }</p><p>  void drop() {</p><p>    ZThread::Guard&lt;ZThread::Mutex&gt; g(lock);</p><p>    taken = false;</p><p>    notTaken.signal();</p><p>  }</p><p>};</p><empty-line/><p>class Philosopher : public ZThread::Runnable {</p><p>  Chopstick&amp; left;</p><p>  Chopstick&amp; right;</p><p>  int id;</p><p>  int ponderFactor;</p><p>  ZThread::CountedPtr&lt;Display&gt; display;</p><p>  int randSleepTime() {</p><p>    if(ponderFactor == 0) return 0;</p><p>    return rand()/(RAND_MAX/ponderFactor) * 250;</p><p>  }</p><p>public:</p><p>  Philosopher(Chopstick&amp; l, Chopstick&amp; r,</p><p>  ZThread::CountedPtr&lt;Display&gt;&amp; disp, int ident,int ponder)</p><p>  : left(l), right(r), display(disp),</p><p>    id(ident), ponderFactor(ponder) { srand(time(0)); }</p><p>  virtual void run() {</p><p>    try {</p><p>      while(!ZThread::Thread::interrupted()) {</p><p>        {</p><p>          std::ostringstream os;</p><p>          os &lt;&lt; *this &lt;&lt; " thinking" &lt;&lt; std::endl;</p><p>          display-&gt;output(os);</p><p>        }</p><p>        ZThread::Thread::sleep(randSleepTime());</p><p>        // Hungry</p><p>        {</p><p>          std::ostringstream os;</p><p>          os &lt;&lt; *this &lt;&lt; " grabbing right" &lt;&lt; std::endl;</p><p>          display-&gt;output(os);</p><p>        }</p><p>        right.take();</p><p>        {</p><p>          std::ostringstream os;</p><p>          os &lt;&lt; *this &lt;&lt; " grabbing left" &lt;&lt; std::endl;</p><p>          display-&gt;output(os);</p><p>        }</p><p>        left.take();</p><p>        // Eating</p><p>        {</p><p>          std::ostringstream os;</p><p>          os &lt;&lt; *this &lt;&lt; " eating" &lt;&lt; std::endl;</p><p>          display-&gt;output(os);</p><p>        }</p><p>        ZThread::Thread::sleep(randSleepTime());</p><p>        right.drop();</p><p>        left.drop();</p><p>      }</p><p>    } catch(ZThread::Synchronization_Exception&amp; e) {</p><p>      std::ostringstream os;</p><p>      os &lt;&lt; *this &lt;&lt; " " &lt;&lt; e.what() &lt;&lt; std::endl;</p><p>      display-&gt;output(os);</p><p>    }</p><p>  }</p><p>  friend std::ostream&amp;</p><p>  operator&lt;&lt;(std::ostream&amp; os, const Philosopher&amp; p) {</p><p>    return os &lt;&lt; "Philosopher " &lt;&lt; p.id;</p><p>  }</p><p>};</p><p>#endif // DININGPHILOSOPHERS_H ///:~</p><empty-line/><p>No two <strong>Philosopher</strong>s can <strong>take( )</strong> a <strong>Chopstick</strong> at the same time, since <strong>take( )</strong> is synchronized with a <strong>Mutex</strong>. In addition, if the chopstick has already been taken by one <strong>Philosopher</strong>, another can <strong>wait( )</strong> on the <strong>available Condition</strong> until the <strong>Chopstick</strong> becomes available when the current holder calls <strong>drop( )</strong> (which must also be synchronized to prevent race conditions).</p><p>Each <strong>Philosopher</strong> holds references to their left and right <strong>Chopstick</strong> so they can attempt to pick those up. The goal of the <strong>Philosopher</strong> is to think part of the time and eat part of the time, and this is expressed in <strong>main( )</strong>. However, you will observe that if the <strong>Philosopher</strong>s spend very little time thinking, they will all be competing for the <strong>Chopstick</strong>s while they try to eat, and deadlock will happen much more quickly. So you can experiment with this, the <strong>ponderFactor</strong> weights the length of time that a <strong>Philosopher</strong> tends to spend thinking and eating. A smaller <strong>ponderFactor</strong> will increase the probability of deadlock.</p><p>In <strong>Philosopher::run( )</strong>, each <strong>Philosopher</strong> just thinks and eats continuously. You see the <strong>Philosopher</strong> thinking for a randomized amount of time, then trying to <strong>take( )</strong> the <strong>right</strong> and then the <strong>left Chopstick</strong>, eating for a randomized amount of time, and then doing it again. Output to the console is synchronized as seen earlier in this chapter.</p><p>This problem is interesting because it demonstrates that a program can appear to run correctly but actually be deadlock prone. To show this, the command-line argument allows you to adjust a factor to affect the amount of time each philosopher spends thinking. If you have lots of philosophers and/or they spend a lot of time thinking, you may never see the deadlock even though it remains a possibility. A command-line argument of zero tends to make it deadlock fairly quickly:<a l:href="#n128" type="note">[128]</a></p><p>//: C11:DeadlockingDiningPhilosophers.cpp</p><p>// Dining Philosophers with Deadlock</p><p>//{L} ZThread</p><p>#include "DiningPhilosophers.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include &lt;cstdlib&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  int ponder = argc &gt; 1 ? atoi(argv[1]) : 5;</p><p>  cout &lt;&lt; "Press &lt;ENTER&gt; to quit" &lt;&lt; endl;</p><p>  static const int sz = 5;</p><p>  try {</p><p>    CountedPtr&lt;Display&gt; d(new Display);</p><p>    ThreadedExecutor executor;</p><p>    Chopstick c[sz];</p><p>    for(int i = 0; i &lt; sz; i++) {</p><p>      int j = (i+1) &gt; (sz-1) ? 0 : (i+1);</p><p>      executor.execute(</p><p>        new Philosopher(c[i], c[j], d, i, ponder));</p><p>    }</p><p>    cin.get();</p><p>    executor.interrupt();</p><p>    executor.wait();</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>Note that the <strong>Chopstick </strong>objects do not need internal identifiers; they are identified by their position in the array <strong>c</strong>. Each <strong>Philosopher</strong> is given a reference to a left and right <strong>Chopstick</strong> object when constructed; these are the utensils that must be picked up before that <strong>Philosopher</strong> can eat. Every <strong>Philosopher</strong> except the last one is initialized by situating that <strong>Philosopher</strong> between the next pair of <strong>Chopstick</strong> objects. The last <strong>Philosopher</strong> is given the zeroth <strong>Chopstick</strong> for its right <strong>Chopstick</strong>, so the round table is completed. That’s because the last <strong>Philosopher</strong> is sitting right next to the first one, and they both share that zeroth chopstick. With this arrangement, it’s possible at some point for all the philosophers to be trying to eat and waiting on the philosopher next to them to put down their chopstick, and the program will deadlock.</p><p>If the <strong>ponder </strong>value is nonzero, you can show that if your threads (philosophers) are spending more time on other tasks (thinking) than eating, then they have a much lower probability of requiring the shared resources (chopsticks), and thus you can convince yourself that the program is deadlock free, even though it isn’t.</p><p>To repair the problem, you must understand that deadlock can occur if four conditions are simultaneously met:</p><p>1.       Mutual exclusion. At least one resource used by the threads must not be shareable. In this case, a chopstick can be used by only one philosopher at a time.</p><p>2.      At least one process must be holding a resource and waiting to acquire a resource currently held by another process. That is, for deadlock to occur, a philosopher must be holding one chopstick and waiting for the other one.</p><p>3.      A resource cannot be preemptively taken away from a process. All processes must only release resources as a normal event. Our philosophers are polite, and they don’t grab chopsticks from other philosophers.</p><p>4.      A circular wait must happen, whereby a process waits on a resource held by another process, which in turn is waiting on a resource held by another process, and so on, until one of the processes is waiting on a resource held by the first process, thus gridlocking everything. In <strong>DeadlockingDiningPhilosophers.cpp</strong>, the circular wait happens because each philosopher tries to get the right chopstick first and then the left.</p><p>Because all these conditions must be met to cause deadlock, you need to stop only one of them from occurring to prevent deadlock. In this program, the easiest way to prevent deadlock is to break condition four. This condition happens because each philosopher is trying to pick up their chopsticks in a particular sequence: first right, then left. Because of that, it’s possible to get into a situation in which each of them is holding their right chopstick and waiting to get the left, causing the circular wait condition. However, if the last philosopher is initialized to try to get the left chopstick first and then the right, that philosopher will never prevent the philosopher on the immediate right from picking up their left chopstick. In this case, the circular wait is prevented. This is only one solution to the problem, but you could also solve it by preventing one of the other conditions (see advanced threading books for more details):</p><p>//: C11:FixedDiningPhilosophers.cpp</p><p>// Dining Philosophers without Deadlock</p><p>//{L} ZThread</p><p>#include "DiningPhilosophers.h"</p><p>#include "zthread/ThreadedExecutor.h"</p><p>#include &lt;cstdlib&gt;</p><p>using namespace ZThread;</p><p>using namespace std;</p><empty-line/><p>int main(int argc, char* argv[]) {</p><p>  int ponder = argc &gt; 1 ? atoi(argv[1]) : 5;</p><p>  cout &lt;&lt; "Press &lt;ENTER&gt; to quit" &lt;&lt; endl;</p><p>  static const int sz = 5;</p><p>  try {</p><p>    CountedPtr&lt;Display&gt; d(new Display);</p><p>    ThreadedExecutor executor;</p><p>    Chopstick c[sz];</p><p>    for(int i = 0; i &lt; sz; i++) {</p><p>      int j = (i+1) &gt; (sz-1) ? 0 : (i+1);</p><p>      if(i &lt; (sz-1))</p><p>        executor.execute(</p><p>          new Philosopher(c[i], c[j], d, i, ponder));</p><p>      else</p><p>        executor.execute(</p><p>          new Philosopher(c[j], c[i], d, i, ponder));</p><p>    }</p><p>    cin.get();</p><p>    executor.interrupt();</p><p>    executor.wait();</p><p>  } catch(Synchronization_Exception&amp; e) {</p><p>    cerr &lt;&lt; e.what() &lt;&lt; endl;</p><p>  }</p><p>} ///:~</p><empty-line/><p>By ensuring that the last philosopher picks up and puts down their left chopstick before their right, the deadlock is removed, and the program will run smoothly.</p><p>There is no language support to help prevent deadlock; it’s up to you to avoid it by careful design. These are not comforting words to the person who’s trying to debug a deadlocking program.</p></section><section><title><p>Summary</p></title><p>The goal of this chapter was to give you the foundations of concurrent programming with threads:</p><p>1.       You can (at least in appearance) run multiple independent tasks.</p><p>2.      You must consider all the possible problems when these tasks shut down. Objects or other tasks may disappear before tasks are finished with them.</p><p>3.      Tasks can collide with each other over shared resources. The mutex is the basic tool used to prevent these collisions.</p><p>4.      Tasks can deadlock if they are not carefully designed.</p><p>However, there are multiple additional facets of threading and tools to help you solve threading problems. The ZThreads library contains a number of these tools, such as <emphasis>semaphores</emphasis> and special types of queues, similar to the one you saw in this chapter. Explore that library as well as other resources on threading to gain more in-depth knowledge.</p><p>It is vital to learn when to use concurrency and when to avoid it. The main reasons to use it are: </p><p>·         To manage a number of tasks whose intermingling will make more efficient use of the computer (including the ability to transparently distribute the tasks across multiple CPUs). </p><p>·         To allow better code organization.</p><p>·         To be more convenient for the user.</p><p>The classic example of resource balancing is to use the CPU during I/O waits. The classic example of user convenience is to monitor a "stop" button during long downloads.</p><p>An additional advantage to threads is that they provide "light" execution context switches (on the order of 100 instructions) rather than "heavy" process context switches (thousands of instructions). Since all threads in a given process share the same memory space, a light context switch changes only program execution and local variables. A process change—the heavy context switch—must exchange the full memory space.</p><p>The main drawbacks to multithreading are: </p><p>·         Slowdown occurs while waiting for shared resources.</p><p>·         Additional CPU overhead is required to manage threads.</p><p>·         Unrewarded complexity arises from poor design decisions.</p><p>·         Opportunities are created for pathologies such as starving, racing, deadlock, and livelock.</p><p>·         Inconsistencies occur across platforms. When developing the original material (in Java) for this chapter, we discovered race conditions that quickly appeared on some computers but that wouldn’t appear on others. The C++ examples in this chapter behaved differently (but usually acceptably) under different operating systems. If you develop a program on a computer and things seem to work right, you might get an unwelcome surprise when you distribute it.</p><p>One of the biggest difficulties with threads occurs because more than one thread might be sharing a resource—such as the memory in an object—and you must make sure that multiple threads don’t try to read and change that resource at the same time. This requires judicious use of synchronization tools, which must be thoroughly understood because they can quietly introduce deadlock situations.</p><p>In addition, there’s a certain art to the application of threads. C++ is designed to allow you to create as many objects as you need to solve your problem—at least in theory. (Creating millions of objects for an engineering finite-element analysis, for example, might not be practical.) However, there is usually an upper bound to the number of threads you’ll want to create, because at some number, threads may become balky. This critical point can be difficult to detect and will often depend on the OS and thread library; it could be fewer than a hundred or in the thousands. As you often create only a handful of threads to solve a problem, this is typically not much of a limit; but in a more general design it becomes a constraint.</p><p>Regardless of how simple threading can seem using a particular language or library, consider it a black art. There’s always something you haven’t considered that can bite you when you least expect it. (For example, note that because the dining philosophers problem can be adjusted so that deadlock rarely happens, you can get the impression that everything is OK.) An appropriate quote comes from Guido Van Rossum, creator of the Python programming language:</p><p><emphasis>In any project that is multi-threaded, most bugs will come from threading issues. This is regardless of programming language—it’s a deep, as yet un-understood property of threads.</emphasis></p><p>For more advanced discussions of threading, see <emphasis>Concurrent Programming in Java</emphasis>, 2<sup>nd</sup> Edition, by Doug Lea, Addison-Wesley, 2000.</p></section><section><title><p>Exercises</p></title><p>Solutions to selected exercises can be found in the electronic document <emphasis>The Thinking in C++ Volume 2 Annotated Solution Guide</emphasis>, available for a small fee from <emphasis>www.BruceEckel.com</emphasis>.</p><p>             1.             Inherit a class from <strong>Runnable</strong> and override the <strong>run( )</strong> function. Inside <strong>run( )</strong>, print a message, and then call <strong>sleep( )</strong>. Repeat this three times, and then return from <strong>run( )</strong>. Put a start-up message in the constructor and a shut-down message when the task terminates. Make several thread objects of this type, and run them to see what happens.</p><p>             2.             Modify <strong>BasicThreads.cpp</strong> to make <strong>LiftOff</strong> threads start other <strong>LiftOff</strong> threads.</p><p>             3.             Modify <strong>ResponsiveUI.cpp</strong> to eliminate any possible race conditions. (Assume <strong>bool</strong> operations are not atomic.)</p><p>             4.             In <strong>Incrementer.cpp</strong>, modify the <strong>Count</strong> class to use a single <strong>int</strong> instead of an array of <strong>int</strong>. Explain the resulting behavior.</p><p>             5.             In <strong>EvenChecker.h</strong>, correct the potential problem in the <strong>Generator</strong> class. (Assume <strong>bool</strong> operations are not atomic.)</p><p>             6.             Modify <strong>EvenGenerator.cpp</strong> to use <strong>interrupt( )</strong> instead of quit flags.</p><p>             7.             In <strong>MutexEvenGenerator.cpp</strong>, change the code in <strong>MutexEvenGenerator::nextValue( )</strong> so that the return expression precedes the <strong>release( )</strong> statement and explain what happens.</p><p>             8.             Modify <strong>ResponsiveUI.cpp</strong> to use <strong>interrupt( )</strong> instead of the <strong>quitFlag</strong> approach.</p><p>             9.             Look up the <strong>Singleton </strong>documentation in the ZThreads library. Modify <strong>OrnamentalGarden.cpp</strong> so that the <strong>Display</strong> object is controlled by a <strong>Singleton</strong> to prevent more than one <strong>Display</strong> from being accidentally created.</p><p>        10.             In <strong>OrnamentalGarden.cpp</strong>, change the <strong>Count::increment( )</strong> function so that it does a direct increment of <strong>count</strong>. Now remove the guard and see if that causes a failure. Is this safe and reliable?</p><p>         11.             Modify <strong>OrnamentalGarden.cpp</strong> so that it uses <strong>interrupt( )</strong> instead of the <strong>pause( )</strong> mechanism. Make sure that your solution doesn’t prematurely destroy objects.</p><p>         12.             Generate assembly code from C++ examples to discover which operations (<strong>bool</strong> assignment, <strong>int </strong>increment, and so on) your particular compiler performs atomically.</p><p>         13.             Modify <strong>WaxOMatic.cpp</strong> by adding more instances of the <strong>Process</strong> class so that it applies and polishes three coats of wax instead of just one.</p><p>         14.             Create two <strong>Runnable</strong> subclasses, one with a <strong>run( )</strong> that starts up and then calls <strong>wait( )</strong>. The other class’s <strong>run( )</strong> should capture the reference of the first <strong>Runnable </strong>object. Its <strong>run( ) </strong>should call <strong>signal( )</strong> for the first thread after some number of seconds have passed so that first thread can print a message.</p><p>         15.             Create an example of a "busy wait." One thread sleeps for awhile and then sets a flag to <strong>true</strong>. The second thread watches that flag inside a <strong>while</strong> loop (this is the "busy wait") and, when the flag becomes <strong>true</strong>, sets it back to <strong>false</strong> and reports the change to the console. Note how much wasted time the program spends inside the "busy wait," and create a second version of the program that uses <strong>wait( )</strong> instead of the "busy wait." Extra: run a profiler to show the time used by the CPU in each case.</p><p>         16.             Modify <strong>ToastOMaticMarkII.cpp</strong> to create peanut-butter and jelly on toast sandwiches using two separate assembly lines and an output <strong>TQueue</strong> for the finished sandwiches. Use a <strong>Reporter</strong> object as in <strong>CarBuilder.cpp</strong> to display the results.</p><p>         17.             Rewrite <strong>C07:BankTeller.cpp</strong> to use real threading instead of simulated threading.</p><p>         18.             Modify <strong>CarBuilder.cpp</strong> to give identifiers to the robots, and add more instances of the different kinds of robots. Note whether all robots get utilized.</p><p>         19.             Modify <strong>CarBuilder.cpp</strong> to add another stage to the car-building process, whereby you add the exhaust system, body, and fenders. As with the first stage, assume these processes can be performed simultaneously by robots.</p><p>        20.             Modify <strong>CarBuilder.cpp</strong> so that <strong>Car</strong> has synchronized access to all the <strong>bool</strong> variables. Because <strong>Mutex</strong>es cannot be copied, this will require significant changes throughout the program.</p><p>         21.             Using the approach in <strong>CarBuilder.cpp</strong>, model the house-building story that was given in this chapter.</p><p>        22.             Change both of the dining philosophers examples so that the number of <strong>Philosopher</strong>s is controlled on the command line, in addition to the ponder time. Try different values and explain the results.</p><p>        23.             Change <strong>DiningPhilosophers.cpp</strong> so that the <strong>Philosopher</strong>s just pick the next available chopstick. (When a <strong>Philosopher</strong> is done with their chopsticks, they drop them into a bin. When a <strong>Philosopher</strong> wants to eat, they take the next two available chopsticks from the bin.) Does this eliminate the possibility of deadlock? Can you reintroduce deadlock by simply reducing the number of available chopsticks?</p><empty-line/><empty-line/><empty-line/></section></section><section><title><p>A: Recommended reading</p></title><section><title><p>General C++</p></title><section><p><strong>The C++ Programming Language, 3</strong><sup><strong>rd</strong></sup><strong> edition</strong>, by Bjarne Stroustrup (Addison-Wesley 1997). To some degree, the goal of the book that you’re currently holding is to allow you to use Bjarne’s book as a reference. Since his book contains the description of the language by the author of that language, it’s typically the place where you’ll go to resolve any uncertainties about what C++ is or isn’t supposed to do. When you get the knack of the language and are ready to get serious, you’ll need it.</p><p><strong>C++ Primer, 3</strong><sup><strong>rd</strong></sup><strong> Edition</strong>, by Stanley Lippman and Josee Lajoie (Addison-Wesley 1998). Not that much of a primer anymore; it’s evolved into a thick book filled with lots of detail, and the one that I reach for along with Stroustrup’s when trying to resolve an issue. <emphasis>Thinking in C++</emphasis> should provide a basis for understanding the <emphasis>C++ Primer </emphasis>as well as Stroustrup’s book.</p><p><strong>Accelerated C++</strong>, by Andrew Koenig and Barbara Moo (Addison-Wesley, 2000). Takes you through C++ by programming topic instead of language feature. Excellent introductory book.</p><p><strong>The C++ Standard Library</strong>, by Nicolai Josuttis (Addison-Wesley, 1999). Readable tutorial and reference for the entire C++ library, including STL. Assumes familiarity with language concepts.</p><p><strong>STL Tutorial and Reference Guide, 2nd Edition</strong>, by David R. Musser et al (Addison-Wesley, 2001). Gentle but thorough introduction to the concepts underlying STL. Contains an STL reference manual.</p><p><strong>The C++ ANSI/ISO Standard</strong>. This is <emphasis>not</emphasis> free, unfortunately (I certainly didn’t get paid for my time and effort on the Standards Committee—in fact, it cost me a lot of money). But at least you can buy the electronic form in PDF for only $18 at http://www.cssinfo.com.</p></section><section><title><p>Bruce’s books</p></title><p>Listed in order of publication. Not all these are currently available.</p><p><emphasis><strong>Computer Interfacing with Pascal &amp; C</strong></emphasis>, (Self-published via the Eisys imprint, 1988. Only available via <emphasis>www.BruceEckel.com</emphasis>). An introduction to electronics from back when CP/M was still king and DOS was an upstart. I used high-level languages and often the parallel port of the computer to drive various electronic projects. Adapted from my columns in the first and best magazine I wrote for, <emphasis>Micro Cornucopia. </emphasis>(To paraphrase Larry O’Brien, long-time editor of <emphasis>Software Development Magazine</emphasis>: The best computer magazine ever published—they even had plans for building a robot in a flower pot!) Alas, Micro C became lost long before the Internet appeared. Creating this book was an extremely satisfying publishing experience.</p><p><emphasis><strong>Using C++</strong></emphasis>, (Osborne/McGraw-Hill, 1989). One of the first books out on C++. This is out of print and replaced by its second edition, the renamed <emphasis>C++ Inside &amp; Out</emphasis>.</p><p><emphasis><strong>C++ Inside &amp; Out</strong></emphasis>, (Osborne/McGraw-Hill, 1993). As noted, actually the second edition of <strong>Using C++</strong>. The C++ in this book is reasonably accurate, but it's circa 1992 and <emphasis>Thinking in C++</emphasis> is intended to replace it. You can find out more about this book and download the source code at <emphasis>www.BruceEckel.com</emphasis>.</p><p><emphasis><strong>Thinking in C++, 1</strong></emphasis><sup><emphasis><strong>st</strong></emphasis></sup><emphasis><strong> Edition</strong></emphasis>, (Prentice Hall, 1995). Winner of the <emphasis>Software Development Magazine Jolt Award</emphasis> for best book of 1995.</p><p><emphasis><strong>Thinking in C++, 2</strong></emphasis><sup><emphasis><strong>nd</strong></emphasis></sup><emphasis><strong> Edition, Volume 1</strong></emphasis>, (Prentice Hall, 2000). Downloadable from <emphasis>www.BruceEckel.com</emphasis>.</p><p><emphasis><strong>Black Belt C++: the Master’s Collection</strong></emphasis>, Bruce Eckel, editor (M&amp;T Books, 1994). Out of print (often available through out-of-print services on the Web). A collection of chapters by various C++ luminaries based on their presentations in the C++ track at the Software Development Conference, which I chaired. The cover on this book stimulated me to gain control over all future cover designs.</p><p><emphasis><strong>Thinking in Java, 1</strong></emphasis><sup><emphasis><strong>st</strong></emphasis></sup><emphasis><strong> Edition</strong></emphasis>, (Prentice Hall, 1998). The first edition of this book won the <emphasis>Software Development Magazine Productivity Award</emphasis>, the <emphasis>Java Developer’s Journal </emphasis>Editor’s Choice Award, and the <emphasis>JavaWorld Reader’s Choice Award for best book</emphasis>. On the CD ROM in the back of this book, and downloadable from <emphasis>www.BruceEckel.com</emphasis>.</p><p><emphasis><strong>Thinking in Java, 2</strong></emphasis><sup><emphasis><strong>nd</strong></emphasis></sup><emphasis><strong> Edition</strong></emphasis>, (Prentice Hall, 2000). This edition won the <emphasis>JavaWorld Editor’s Choice Award for best book</emphasis>. On the CD ROM in the back of this book, and downloadable from <emphasis>www.BruceEckel.com</emphasis>.</p><p><emphasis><strong>Thinking in Java, 3</strong></emphasis><sup><emphasis><strong>rd</strong></emphasis></sup><emphasis><strong> Edition</strong></emphasis>, (Prentice Hall, 2002). This edition won the <emphasis>Software Development Magazine Jolt Award</emphasis> for best book of 2002, and the <emphasis>Java Developer’s Journal </emphasis>Editor’s Choice Award. The new CD ROM in the back of this book now includes the first seven lectures from the 2<sup>nd</sup> edition of the <emphasis>Hands-On Java CD ROM</emphasis>.</p><p><emphasis><strong>The Hands-On Java CD ROM</strong></emphasis>, 3<sup>rd</sup> edition (MindView, 2003). Over 15 hours of lectures and slides covering the basics of the Java language, based on <emphasis>Thinking in Java, 3</emphasis><sup><emphasis>rd</emphasis></sup><emphasis> Edition</emphasis>. Available only at www.MindView.net.</p></section><section><title><p>Chuck’s books</p></title><p><strong>C &amp; C++ Code Capsules</strong>, by Chuck Allison (Prentice-Hall, 1998). Assumes that you already know C and C++, and covers some of the issues that you may be rusty on, or that you may not have gotten right the first time. This book fills in C gaps as well as C++ gaps.[ ]</p><p><strong>Thinking in C: Foundations for Java &amp; C++</strong>, by Chuck Allison (<emphasis>not actually a book</emphasis>, but a MindView, Inc. Seminar on CD ROM, 1999, bundled with <emphasis>Thinking in Java</emphasis> and <emphasis>Thinking in C++, Volume 1</emphasis>). A multimedia course including lectures and slides in the foundations of the C Language to prepare you to learn Java or C++. This is not an exhaustive course in C; only the necessities for moving on to the other languages are included. An extra section covering features for the C++ programmer is included. Prerequisite: experience with a high-level programming language, such as Pascal, BASIC, FORTRAN, or LISP.</p></section></section><section><title><p>In-depth C++</p></title><p>Books that go more deeply into topics of the language, and help you avoid the typical pitfalls inherent in developing C++ programs.</p><p><strong>Large-Scale C++ Software Design</strong>, by John Lakos (Addison-Wesley, 1996). Motivates and presents in-the-trenches techniques for large C++ projects.</p><p><strong>Effective C++, 2nd Edition</strong>, by Scott Meyers (Addison-Wesley, 1997). Classic book of techniques to improve C++ designs. Codifies many of the things that programmers have to learn the hard way.</p><p><strong>More Effective C++</strong>, by Scott Meyers (Addison-Wesley, 1995) Continuation of <emphasis>Effective C++</emphasis> (above). Another C++ classic.</p><p><strong>Effective STL</strong>, by Scott Meyers (Addison-Wesley, 2001). Extremely practical, in-depth coverage of how to use the STL. Contains expert advice found nowhere else.</p><p><strong>Generic Programming and the STL</strong>, by Matt Austern (Addison-Wesley, 1998). Explores the conceptual underpinnings of the design of the STL. Heavy on theory, but imparts a visionary look into the design of generic libraries.</p><p><strong>Exceptional C++</strong>, by Herb Sutter (Addison-Wesley, 2000). Leads the reader through a progression of problems and their solution. Gives easy-to-remember advice for solid design of modern C++ programs.</p><p><strong>More Exceptional C++</strong>, by Herb Sutter (Addison-Wesley, 2001). Continuation of <emphasis>Exceptional C++</emphasis> (above).</p><p><strong>C++ FAQs, 2nd Edition</strong>, by Marshall Cline, Greg Lomow, and Mike Girou (Addison-Wesley, 1998). Nicely-structured compendium of common C++ questions and their answers. Covers a broad range of topics, from beginner to advanced.</p><p><strong>C++ Gotchas</strong>, by Stephen Dewhurst (Addison-Wesley, 2002). Contemporary catalog of easy-to-discover but hard-to-remedy C++ quirks by a widely-renowned recognized C++ expert.</p><p><strong>C++ Templates, The Complete Guide</strong>, by David Vandervoorde and Nicolai M. Josuttis (Addison-Wesley, 2002). The first and only book devoted completely to templates. The definitive reference.</p><p><strong>Standard C++ IOStreams and Locales</strong>, by Angelika Langer and Klaus Kreft (Addison-Wesley, 2000). The most in-depth coverage of iostreams available. Plumbs the depths of streams implementation and idiomatic use. A handy reference as well as tutorial.</p><p><strong>Design &amp; Evolution of C++</strong>, by Bjarne Stroustrup (Addison-Wesley, 1994). Traces the complete history of C++, documenting the design decisions that were made along the way. If you want to know why C++ is the way it is, this is the book with the answers, written by the designer of the language.</p><p><strong>Modern C++ Design</strong>, by Andrei Alexandrescu (Addison-Wesley, 2001). The standard text on policy-based design in C++. Filled with practical, advanced uses of templates.</p><p><strong>Generative Programming</strong>, by Krzysztof Czarnecki and Ulrich Eisencecker, (Addison-Wesley, 2000). Ground-breaking book on highly-advanced C++ techniques. Takes software automation to the next level.</p><p><strong>Multi-Paradigm Design for C++</strong>, by James O. Coplien (Addison-Wesley, 1998). Advanced text showing how to harmonize the use of procedural, object-oriented, and generic programming for effective C++ designs.</p></section><section><title><p>Design Patterns</p></title><p><strong>Design Patterns</strong>, by Erich Gamma et al (Addison-Wesley, 1995). The revolutionary book that introduced design patterns to the industry. Catalogs a critical of design patterns with motivation and examples (using C++ and a little SmallTalk).</p><p><strong>Pattern-Oriented System Architecture, Volume 1: A System of Patterns</strong>, by Frank Buschmann et al (John Wiley &amp; Son, 1996). Another look at design patterns in practice. Introduces new design patterns.</p><p>[ ]</p></section></section><section><title><p>B: Etc</p></title><p>This appendix contains files that are required to build the files in Volume 2.</p><p>//: :require.h</p><p>// Test for error conditions in programs</p><p>// Local "using namespace std" for old compilers</p><p>#ifndef REQUIRE_H</p><p>#define REQUIRE_H</p><p>#include &lt;cstdio&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;fstream&gt;</p><empty-line/><p>inline void require(bool requirement,</p><p>  const char* msg = "Requirement failed") {</p><p>  using namespace std;</p><p>  if (!requirement) {</p><p>    fputs(msg, stderr);</p><p>    fputs("\n", stderr);</p><p>    exit(EXIT_FAILURE);</p><p>  }</p><p>}</p><empty-line/><p>inline void requireArgs(int argc, int args,</p><p>  const char* msg = "Must use %d arguments") {</p><p>  using namespace std;</p><p>   if (argc != args + 1) {</p><p>     fprintf(stderr, msg, args);</p><p>     fputs("\n", stderr);</p><p>     exit(EXIT_FAILURE);</p><p>   }</p><p>}</p><empty-line/><p>inline void requireMinArgs(int argc, int minArgs,</p><p>  const char* msg =</p><p>    "Must use at least %d arguments") {</p><p>  using namespace std;</p><p>  if(argc &lt; minArgs + 1) {</p><p>    fprintf(stderr, msg, minArgs);</p><p>    fputs("\n", stderr);</p><p>    exit(EXIT_FAILURE);</p><p>  }</p><p>}</p><empty-line/><p>inline void assure(std::ifstream&amp; in,</p><p>  const char* filename = "") {</p><p>  using namespace std;</p><p>  if(!in) {</p><p>    fprintf(stderr,</p><p>      "Could not open file %s\n", filename);</p><p>    exit(EXIT_FAILURE);</p><p>  }</p><p>}</p><empty-line/><p>inline void assure(std::ofstream&amp; in,</p><p>  const char* filename = "") {</p><p>  using namespace std;</p><p>  if(!in) {</p><p>    fprintf(stderr,</p><p>      "Could not open file %s\n", filename);</p><p>    exit(EXIT_FAILURE);</p><p>  }</p><p>}</p><empty-line/><p>inline void assure(std::fstream&amp; in,</p><p>  const char* filename = "") {</p><p>  using namespace std;</p><p>  if(!in) {</p><p>    fprintf(stderr,</p><p>      "Could not open file %s\n", filename);</p><p>    exit(EXIT_FAILURE);</p><p>  }</p><p>}</p><p>#endif // REQUIRE_H ///:~</p><empty-line/><p>//: C0B:Dummy.cpp</p><p>// To give the makefile at least one target</p><p>// for this directory</p><p>int main() {} ///:~</p><empty-line/><p>The <strong>Date</strong> class files:</p><p>//: C02:Date.h</p><p>#ifndef DATE_H</p><p>#define DATE_H</p><p>#include &lt;string&gt;</p><p>#include &lt;stdexcept&gt;</p><p>#include &lt;iosfwd&gt;</p><empty-line/><p>class Date {</p><p>public:</p><p>  // A class for date calculations</p><p>  struct Duration {</p><p>    int years, months, days;</p><p>    Duration(int y, int m, int d)</p><p>    : years(y), months(m) ,days(d) {}</p><p>  };</p><p>  // An exception class</p><p>  struct DateError : public std::logic_error {</p><p>DateError(const std::string&amp; msg = "")</p><p>  : std::logic_error(msg) {}</p><p>  };</p><p>  Date();</p><p>  Date(int, int, int) throw(DateError);</p><p>  Date(const std::string&amp;) throw(DateError);</p><p>  int getYear() const;</p><p>  int getMonth() const;</p><p>  int getDay() const;</p><p>  std::string toString() const;</p><p>  friend Duration duration(const Date&amp;, const Date&amp;);</p><p>  friend bool operator&lt;(const Date&amp;, const Date&amp;);</p><p>  friend bool operator&lt;=(const Date&amp;, const Date&amp;);</p><p>  friend bool operator&gt;(const Date&amp;, const Date&amp;);</p><p>  friend bool operator&gt;=(const Date&amp;, const Date&amp;);</p><p>  friend bool operator==(const Date&amp;, const Date&amp;);</p><p>  friend bool operator!=(const Date&amp;, const Date&amp;);</p><p>  friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp;,</p><p>                   const Date&amp;);</p><p>  friend std::istream&amp; operator&gt;&gt;(std::istream&amp;,</p><p>                                  Date&amp;);</p><p>private:</p><p>  int year, month, day;</p><p>  int compare(const Date&amp;) const;</p><p>  static int daysInPrevMonth(int year, int mon);</p><p>};</p><empty-line/><p>#endif ///:~</p><empty-line/><p>//: C02:Date.cpp {O}</p><p>#include "Date.h"</p><p>#include &lt;iostream&gt;</p><p>#include &lt;sstream&gt;</p><p>#include &lt;cstdlib&gt;</p><p>#include &lt;string&gt;</p><p>#include &lt;algorithm&gt; // for swap()</p><p>#include &lt;ctime&gt;</p><p>#include &lt;cassert&gt;</p><p>#include &lt;iomanip&gt;</p><p>using namespace std;</p><empty-line/><p>namespace {</p><p>  const int daysInMonth[][13] = {</p><p>    {0,31,28,31,30,31,30,31,31,30,31,30,31},</p><p>    {0,31,29,31,30,31,30,31,31,30,31,30,31}};</p><p>  inline bool isleap(int y) {</p><p>    return y%4 == 0 &amp;&amp; y%100 != 0 || y%400 == 0;</p><p>  }</p><p>}</p><empty-line/><p>Date::Date() {</p><p>  // Get current date</p><p>  time_t tval = time(0);</p><p>  struct tm *now = localtime(&amp;tval);</p><p>  year = now-&gt;tm_year + 1900;</p><p>  month = now-&gt;tm_mon + 1;</p><p>  day = now-&gt;tm_mday;</p><p>}</p><empty-line/><p>Date::Date(int yr,int mon,int dy) throw(Date::DateError) {</p><p>  if (!(1 &lt;= mon &amp;&amp; mon &lt;= 12))</p><p>    throw DateError("Bad month in Date ctor");</p><p>  if (!(1 &lt;= dy &amp;&amp; dy &lt;= daysInMonth[isleap(year)][mon]))</p><p>    throw DateError("Bad day in Date ctor");</p><p>  year = yr;</p><p>  month = mon;</p><p>  day = dy;</p><p>}</p><empty-line/><p>Date::Date(const std::string&amp; s) throw(Date::DateError) {</p><p>  // Assume YYYYMMDD format</p><p>  if (!(s.size() == 8))</p><p>    throw DateError("Bad string in Date ctor");</p><p>  for(int n = 8; --n &gt;= 0;)</p><p>    if (!isdigit(s[n]))</p><p>      throw DateError("Bad string in Date ctor");</p><p>  string buf = s.substr(0, 4);</p><p>  year = atoi(buf.c_str());</p><p>  buf = s.substr(4, 2);</p><p>  month = atoi(buf.c_str());</p><p>  buf = s.substr(6, 2);</p><p>  day = atoi(buf.c_str());</p><p>  if (!(1 &lt;= month &amp;&amp; month &lt;= 12))</p><p>    throw DateError("Bad month in Date ctor");</p><p>if (!(1 &lt;= day &amp;&amp; day &lt;=</p><p>  daysInMonth[isleap(year)][month]))</p><p>    throw DateError("Bad day in Date ctor");</p><p>}</p><empty-line/><p>int Date::getYear() const { return year; }</p><empty-line/><p>int Date::getMonth() const { return month; }</p><empty-line/><p>int Date::getDay() const { return day; }</p><empty-line/><p>string Date::toString() const {</p><p>  ostringstream os;</p><p>  os.fill('0');</p><p>  os &lt;&lt; setw(4) &lt;&lt; year</p><p>     &lt;&lt; setw(2) &lt;&lt; month</p><p>     &lt;&lt; setw(2) &lt;&lt; day;</p><p>  return os.str();</p><p>}</p><empty-line/><p>int Date::compare(const Date&amp; d2) const {</p><p>  int result = year - d2.year;</p><p>  if (result == 0) {</p><p>    result = month - d2.month;</p><p>    if (result == 0)</p><p>      result = day - d2.day;</p><p>  }</p><p>  return result;</p><p>}</p><empty-line/><p>int Date::daysInPrevMonth(int year, int month) {</p><p>  if (month == 1) {</p><p>    --year;</p><p>    month = 12;</p><p>  }</p><p>  else</p><p>    --month;</p><p>  return daysInMonth[isleap(year)][month];</p><p>}</p><empty-line/><p>bool operator&lt;(const Date&amp; d1, const Date&amp; d2) {</p><p>  return d1.compare(d2) &lt; 0;</p><p>}</p><p>bool operator&lt;=(const Date&amp; d1, const Date&amp; d2) {</p><p>  return d1 &lt; d2 || d1 == d2;</p><p>}</p><p>bool operator&gt;(const Date&amp; d1, const Date&amp; d2) {</p><p>  return !(d1 &lt; d2) &amp;&amp; !(d1 == d2);</p><p>}</p><p>bool operator&gt;=(const Date&amp; d1, const Date&amp; d2) {</p><p>  return !(d1 &lt; d2);</p><p>}</p><p>bool operator==(const Date&amp; d1, const Date&amp; d2) {</p><p>  return d1.compare(d2) == 0;</p><p>}</p><p>bool operator!=(const Date&amp; d1, const Date&amp; d2) {</p><p>  return !(d1 == d2);</p><p>}</p><empty-line/><p>Date::Duration</p><p>duration(const Date&amp; date1, const Date&amp; date2) {</p><p>  int y1 = date1.year;</p><p>  int y2 = date2.year;</p><p>  int m1 = date1.month;</p><p>  int m2 = date2.month;</p><p>  int d1 = date1.day;</p><p>  int d2 = date2.day;</p><empty-line/><p>  // Compute the compare</p><p>  int order = date1.compare(date2);</p><p>  if (order == 0)</p><p>    return Date::Duration(0,0,0);</p><p>  else if (order &gt; 0) {</p><p>    // Make date1 precede date2 locally</p><p>    using std::swap;</p><p>    swap(y1, y2);</p><p>    swap(m1, m2);</p><p>    swap(d1, d2);</p><p>  }</p><empty-line/><p>  int years = y2 - y1;</p><p>  int months = m2 - m1;</p><p>  int days = d2 - d1;</p><p>  assert(years &gt; 0 ||</p><p>     years == 0 &amp;&amp; months &gt; 0 ||</p><p>     years == 0 &amp;&amp; months == 0 &amp;&amp; days &gt; 0);</p><empty-line/><p>  // Do the obvious corrections (must adjust days</p><p>  // before months!) - This is a loop in case the</p><p>  // previous month is February, and days &lt; -28.</p><p>  int lastMonth = m2;</p><p>  int lastYear = y2;</p><p>  while (days &lt; 0) {</p><p>    // Borrow from month</p><p>    assert(months &gt; 0);</p><p>    days += Date::daysInPrevMonth(</p><p>      lastYear, lastMonth--);</p><p>    --months;</p><p>  }</p><empty-line/><p>  if (months &lt; 0) {</p><p>    // Borrow from year</p><p>    assert(years &gt; 0);</p><p>    months += 12;</p><p>    --years;</p><p>  }</p><p>  return Date::Duration(years, months, days);</p><p>}</p><empty-line/><p>ostream&amp; operator&lt;&lt;(ostream&amp; os, const Date&amp; d) {</p><p>  char fillc = os.fill('0');</p><p>  os &lt;&lt; setw(2) &lt;&lt; d.getMonth() &lt;&lt; ‘-‘</p><p>     &lt;&lt; setw(2) &lt;&lt; d.getDay() &lt;&lt; ‘-‘</p><p>     &lt;&lt; setw(4) &lt;&lt; setfill(fillc) &lt;&lt; d.getYear();</p><p>  return os;</p><p>}</p><empty-line/><p>istream&amp; operator&gt;&gt;(istream&amp; is, Date&amp; d) {</p><p>  is &gt;&gt; d.month;</p><p>  char dash;</p><p>  is &gt;&gt; dash;</p><p>  if (dash != '-')</p><p>    is.setstate(ios::failbit);</p><p>  is &gt;&gt; d.day;</p><p>  is &gt;&gt; dash;</p><p>  if (dash != '-')</p><p>    is.setstate(ios::failbit);</p><p>  is &gt;&gt; d.year;</p><p>  return is;</p><p>} ///:~</p><empty-line/><p>The file test.txt used in Chapter 6:</p><p>//: C06:Test.txt</p><p>f a f d A  G f d F a A F h f A d f f a a</p><p>///:~</p><empty-line/><empty-line/><image l:href="#15"/></section><section><title><p>Index</p></title><p>&lt;</p><p>&lt;exception&gt; · 59</p><p>&lt;memory&gt; · 55</p><p>&lt;stdexcept&gt; · 59</p><p>A</p><p>abort( ): Standard C library function · 46</p><p>abstraction: in program design · 664</p><p>ANSI/ISO C++ committee · 25</p><p>applicator · 231</p><p>applying a function to a container · 289</p><p>arguments: variable argument list · 181</p><p>atof( ) · 209</p><p>atoi( ) · 209</p><p>atomic operation · 763</p><p>auto_ptr · 55</p><p>automatic type conversion: and exception handling · 42</p><p>awk · 234</p><p>B</p><p>bad_cast: Standard C++ library exception type · 61</p><p>bad_exception class · 65</p><p>bad_typeid: Standard C++ library exception type · 61</p><p>before( ): run-time type identification · 607</p><p>behavioral design patterns · 673</p><p>blocking: and threads · 764</p><p>blocking and mutexes · 767</p><p>book errors, reporting · 26</p><p>broadcast( ) · 765</p><p>broadcast( ), threading · 772, 787</p><p>buffering, iostream · 200</p><p>busy wait · 762</p><p>busy wait, threading · 773</p><p>bytes, reading raw · 191</p><p>C</p><p>C: basic data types · 181; error handling in C · 34; rand( ), Standard library · 246; Standard C · 25; Standard C library function abort( ) · 46</p><p>C++: ANSI/ISO C++ committee · 25; Standard C++ · 25; Standard string class · 182</p><p>C++ standards committee: and concurrency · 721</p><p>cancel( ), function in ZThread threading library · 746</p><p>Cancelable, ZThread threading library · 746</p><p>cast: run-time type identification, casting to intermediate levels · 608</p><p>catch · 39, 41; catching any exception · 44</p><p>chaining, in iostreams · 185</p><p>change: vector of change · 664</p><p>character: transforming strings to typed values · 209</p><p>class: class hierarchies and exception handling · 43; maintaining library source · 235; Standard C++ string · 182; wrapping · 176</p><p>cleaning up the stack during exception handling · 48</p><p>cohesion · 71</p><p>command line: interface · 188</p><p>committee, ANSI/ISO C++ · 25</p><p>compile time: error checking · 181</p><p>compiler error tests · 240</p><p>composition: and design patterns · 665</p><p>concurrency · 719; blocking · 764; when to use it · 803</p><p>ConcurrentExecutor (Concurrency) · 732</p><p>Condition class, threading · 772</p><p>console I/O · 188</p><p>constructor: and exception handling · 50; default constructor · 696; default constructor synthesized by the compiler · 666; exception handling · 48, 80; failing · 80; order of constructor and destructor calls · 610; private constructor · 666; simulating virtual constructors · 691; virtual functions inside constructors · 692</p><p>conversion, automatic type conversions and exception handling · 42</p><p>cooperation between threads · 771</p><p>Coplien, James · 693</p><p>CountedPtr, reference-counting template in ZThread library (Concurrency) · 743</p><p>covariance: exception specifications · 69</p><p>Crahen, Eric · 722</p><p>creating: manipulators · 230</p><p>creational design patterns · 672</p><p>critical section, in thread programming · 749</p><p>Cygwin: and ZThreads · 724</p><p>D</p><p>data: C data types · 181</p><p>datalogger · 242</p><p>dead, thread · 764</p><p>deadlock: conditions for · 800</p><p>deadlock, concurrency · 750</p><p>deadlock, concurrency (multithreading) · 795</p><p>decimal: dec in iostreams · 225; dec manipulator in iostreams · 225; formatting · 217</p><p>default: constructor · 696</p><p>default constructor: synthesized by the compiler · 666</p><p>design: abstraction in program design · 664; cohesion · 71; exception-neutral · 74; exception-safe · 70</p><p>design patterns · 663; behavioral · 673; creational · 672; observer · 699; structural · 672; vector of change · 664; visitor · 714</p><p>destructor: and exception handling · 48; exception handling · 80; order of constructor and destructor calls · 610</p><p>dining philosophers, threading · 795</p><p>dispatching: double dispatching · 711; multiple dispatching · 710</p><p>domain_error: Standard C++ library exception type · 61</p><p>double dispatching · 711</p><p>dynamic_cast: difference between dynamic_cast and typeid( ), run-time type identification · 609</p><p>E</p><p>efficiency: and threads · 721; run-time type identification · 613</p><p>ellipses, with exception handling · 44</p><p>endl, iostreams · 225</p><p>errno · 34</p><p>error: compile-time checking · 181; error handling in C · 34; handling · 33; recovery · 33; reporting errors in book · 26</p><p>error handling · 33</p><p>exception · 33; and ZThreads (Concurrency) · 737; catching an · 41; catching any · 45; catching by reference · 42; catching via accessible base · 44; handler · 39; rethrowing an · 45, 74; re-throwing an · 45; safety · 70; throwing an · 38; uncaught · 48</p><p>exception class · 58; what( ) · 59</p><p>exception handling · 33; asynchronous events · 76; atomic allocations for safety · 52; automatic type conversions · 42; bad_cast Standard C++ library exception type · 61; bad_exception class · 65; bad_typeid Standard C++ library exception type · 61; catching any exception · 44; class hierarchies · 43; cleaning up the stack during a throw · 48; constructors · 48, 50, 80; destructors · 48, 56, 80; domain_error Standard C++ library exception type · 61; ellipses · 44; exception class · 58; exception class, what( ) · 59; exception handler · 39; exception hierarchies · 79; exception matching · 42; exception Standard C++ library exception type · 60; incomplete objects · 48; inheritance · 43; invalid_argument Standard C++ library exception type · 61; length_error Standard C++ library exception type · 61; logic_error Standard C++ library exception type · 60; memory leaks · 48; multiple inheritance · 79; naked pointers · 50; object slicing and exception handling · 42; out_of_range Standard C++ library exception type · 61; overhead of · 81; programming guidelines · 75; references · 54, 80; resource management · 50; runtime_error class · 58; runtime_error Standard C++ library exception type · 60; set_terminate( ) · 46; set_unexpected( ) · 63; specification · 62; specifications and inheritance · 68; specifications, covariance · 69; specifications, when not to use · 70; stack unwinding · 38; Standard C++ library exception type · 60; Standard C++ library exceptions · 58; terminate( ) · 65; termination vs. resumption · 41; testing · 104; throwing &amp; catching pointers · 80; throwing an exception · 37; typical uses of exceptions · 77; uncaught exceptions · 45; unexpected( ) · 63; when to avoid · 75; zero-cost model · 83</p><p>exception hierarchies · 79</p><p>exception neutral · 74</p><p>exception safety · 70</p><p>exception specifications · 62; covariance of · 69; inheritance · 68; when not to use · 70</p><p>exclusion, mutual, in threads · 749</p><p>Executors, ZThread (Concurrency) · 731</p><p>exeption handling: logic_error class · 58</p><p>extensible program · 181</p><p>extractor · 184</p><p>F</p><p>file: iostreams · 182, 188</p><p>FILE, stdio · 177</p><p>fill: width, precision, iostream · 219</p><p>flags, iostreams format · 215</p><p>flock( ), and SynchronousExecutor (Concurrency) · 733</p><p>flush, iostreams · 224, 225</p><p>format flags, iostreams · 215</p><p>formatting: formatting manipulators, iostreams · 224; in-core · 207; iostream internal data · 215; output stream · 214</p><p>fseek( ) · 203</p><p>FSTREAM.H · 197</p><p>function: applying a function to a container · 289; function templates · 279; pointer to a function · 47</p><p>Function-level try blocks · 56</p><p>G</p><p>get pointer · 205</p><p>get( ) · 190, 198; overloaded versions · 191; with streambuf · 202</p><p>getline( ) · 190, 198</p><p>getPriority( ) · 739</p><p>goto: non-local goto, setjmp( ) and longjmp( ) · 35</p><p>graphical user interface (GUI) · 188</p><p>Guard template, ZThread (concurrency) · 750</p><p>GUI: graphical user interface · 188</p><p>H</p><p>handler, exception · 39</p><p>handshaking, between concurrent tasks · 772</p><p>hex · 225</p><p>hex (hexadecimal) in iostreams · 225</p><p>hex( ) · 218</p><p>hexadecimal · 217</p><p>hierarchy: object-based hierarchy · 622</p><p>I</p><p>I/O: and threads, blocking · 767; console · 188</p><p>ifstream · 182, 196, 202</p><p>ignore( ) · 198</p><p>in-core formatting · 207</p><p>inheritance: and design patterns · 664; multiple inheritance and run-time type identification · 608, 611, 619</p><p>initialization: controlling initialization order · 667</p><p>Initialization: Resource Acquisition Is Initialization · 52</p><p>initialization, lazy · 666</p><p>input: line at a time · 188</p><p>inserter · 184</p><p>interface: command-line · 188; graphical user (GUI) · 188; repairing an interface with multiple inheritance · 655</p><p>interfaces: responsive user · 728</p><p>interpreter, printf( ) run-time · 180</p><p>interrupt( ), threading · 765</p><p>interrupted status, threading · 769</p><p>Interrupted_Exception, threading · 769</p><p>invalid_argument: Standard C++ library exception type · 61</p><p>iostream: and threads (concurrency), colliding output · 757</p><p>IOSTREAM.H · 197</p><p>iostreams: applicator · 231; automatic · 219; buffering · 200; dec · 225; dec (decimal) · 225; endl · 225; files · 188; <strong>fixed</strong> · 227; flush · 224, 225; format flags · 215; formatting manipulators · 224; fseek( ) · 203; get( ) · 198; getline( ) · 198; hex · 225; hex (hexadecimal) · 225; ignore( ) · 198; <strong>internal</strong> · 226; internal formatting data · 215; ios::basefield · 217; ios::beg · 204; ios::cur · 204; <strong>ios::dec</strong> · 218; ios::end · 204; <strong>ios::fill( )</strong> · 220; <strong>ios::fixed</strong> · 218; ios::flags( ) · 215; <strong>ios::hex</strong> · 218; <strong>ios::internal</strong> · 219; <strong>ios::left</strong> · 219; <strong>ios::oct</strong> · 218; <strong>ios::precision( )</strong> · 220; <strong>ios::right</strong> · 219; <strong>ios::scientific</strong> · 218; <strong>ios::showbase</strong> · 216; <strong>ios::showpoint</strong> · 216; <strong>ios::showpos</strong> · 216; <strong>ios::skipws</strong> · 216; <strong>ios::unitbuf</strong> · 216; <strong>ios::uppercase</strong> · 216; <strong>ios::width( )</strong> · 220; <strong>left</strong> · 226; manipulators, creating · 230; <strong>noshowbase</strong> · 225; <strong>noshowpoint</strong> · 226; <strong>noshowpos</strong> · 226; <strong>noskipws</strong> · 226; <strong>nouppercase</strong> · 226; oct (octal) · 225; open modes · 199; precision( ) · 244; rdbuf( ) · 201; <strong>resetiosflags</strong> · 227; <strong>right</strong> · 226; <strong>scientific</strong> · 227; seekg( ) · 204; seeking in · 203; seekp( ) · 204; <strong>setbase</strong> · 227; setf( ) · 215, 244; <strong>setfill</strong> · 227; <strong>setiosflags</strong> · 227; <strong>setprecision</strong> · 228; <strong>showbase</strong> · 225; <strong>showpoint</strong> · 226; <strong>showpos</strong> · 226; <strong>skipws</strong> · 226; tellg( ) · 204; tellp( ) · 204; <strong>uppercase</strong> · 226; width, fill and precision · 219; ws · 225</p><p>istream · 182</p><p><strong>istringstreams</strong> · 182</p><p>istrstream · 207</p><p>iterator · 665</p><p>J</p><p>Java: and concurrency/threads · 722</p><p>Josee Lajoie · 84</p><p>K</p><p>keyword: catch · 39</p><p>L</p><p>lazy initialization · 666</p><p>length_error: Standard C++ library exception type · 61</p><p>library: maintaining class source · 235</p><p>LIMITS.H · 234</p><p>line input · 188</p><p>Linux: and ZThreads · 724</p><p>logic_error: Standard C++ library exception type · 60</p><p>logic_error class · 58</p><p>longjmp( ) · 35</p><p>M</p><p>maintaining class library source · 235</p><p>manipulator: creating · 230; iostreams formatting · 224</p><p>memory management, and threads · 740</p><p>modes, iostream open · 199</p><p>modulus operator · 247</p><p>monolithic · 622</p><p>multiple dispatching · 710</p><p>multiple inheritance: and run-time type identification · 608, 611, 619; duplicate subobjects · 635; exception handling · 79; repairing an interface · 655</p><p>multiprocessor machine, and threading · 720</p><p>multitasking · 719</p><p>multithreading · 719; drawbacks · 803</p><p>multithreading library for C++, ZThread · 722</p><p>mutex: ZThread FastMutex · 761</p><p>mutex, simplifying with the Guard template · 750</p><p>mutex, threading · 772</p><p>mutual exclusion, in threads · 749</p><p>N</p><p>naked pointers, and exception handling · 50</p><p>non-local goto: setjmp( ) and longjmp( ) · 35</p><p>notifyObservers( ) · 699, 702</p><p>O</p><p>object: object-based hierarchy · 622; slicing, and exception handling · 42; temporary · 234</p><p>Observable · 699</p><p>observer design pattern · 699</p><p>oct · 225</p><p>ofstream · 182, 196</p><p>open modes, iostreams · 199</p><p>operator: [] · 54; &lt;&lt; · 184; &gt;&gt; · 184; modulus · 247</p><p>optimization: throughput, with threading · 720</p><p>order: of constructor and destructor calls · 610</p><p>order, controlling initialization · 667</p><p>ostream · 182, 198</p><p>ostringstreams · 182</p><p>ostrstream · 207</p><p>out_of_range: Standard C++ library exception type · 61</p><p>output: stream formatting · 214</p><p>overhead: exception handling · 81</p><p>P</p><p>Park, Nick · 291</p><p>patterns, design patterns · 663</p><p>perror( ) · 34</p><p>philosophers, dining and threading · 795</p><p>pointer: pointer to a function · 47</p><p>polymorphism · 613</p><p>PoolExecutor (Concurrency) · 732</p><p>precision: width, fill, iostream · 219</p><p>precision( ) · 244</p><p>preprocessor: stringizing · 222</p><p>printf( ) · 180, 214; error code · 33; run-time interpreter · 180</p><p>priority, thread · 738</p><p>private: constructor · 666</p><p>process, and threading · 719</p><p>producer-consumer, threading · 777</p><p>put pointer · 204</p><p>Q</p><p>queues, thread, for problem-solving · 781</p><p>R</p><p>race condition · 746</p><p>RAII · 52, 56</p><p>raise( ) · 34</p><p>rand( ) · 246</p><p>RAND_MAX · 247</p><p>raw, reading bytes · 191</p><p>rdbuf( ) · 201</p><p>read( ) · 191</p><p>reading raw bytes · 191</p><p>reference: and exception handling · 80; exception handling · 54</p><p>reference counting, and ZThreads (Concurrency) · 741</p><p>reporting errors in book · 26</p><p>Resource: Acquisition Is Initialization · 52</p><p>Resource Acquisition Is Initialization · 52</p><p>responsive user interfaces · 728</p><p>resumption: termination vs. resumption, exception handling · 41</p><p>rethrow: an exception · 45; exception · 74</p><p>Runnable · 724</p><p>run-time interpreter for printf( ) · 180</p><p>run-time type identification · 599; and efficiency · 613; and multiple inheritance · 608, 611, 619; and templates · 610; and void pointers · 609; before( ) · 607; casting to intermediate levels · 608; difference between dynamic_cast and typeid( ) · 609; mechanism &amp; overhead · 619; misuse · 612; typeinfo · 619; VTABLE · 619; when to use it · 612</p><p>runtime_error: Standard C++ library exception type · 60</p><p>S</p><p>Scott Meyers · 84</p><p>sed · 234</p><p>seekg( ) · 204</p><p>seeking in iostreams · 203</p><p>seekp( ) · 204</p><p>serialization · 247</p><p>serialization, thread · 781</p><p>set: STL set class example · 475</p><p>set_terminate( ) · 46</p><p>set_unexpected( ) · 63; exception handling · 63</p><p>setChanged( ) · 702</p><p>setf( ), iostreams · 215, 244</p><p>setjmp( ) · 35</p><p>setPriority( ) · 740</p><p>signal( ) · 34, 76, 764</p><p>signal( ), threading · 772</p><p>simulating virtual constructors · 691</p><p>Singleton · 665; and ZThreads library (concurrency) · 758; implemented with Curiously Recurring Template Pattern · 670; Meyers’ Singleton · 669</p><p>sleep( ) · 764; threading · 736</p><p>slicing: object slicing and exception handling · 42</p><p>Smalltalk · 622</p><p>specification: exception · 62</p><p>stack unwinding · 38</p><p>standard: Standard C · 25; Standard C++ · 25</p><p>Standard C++ libraries: string class · 182</p><p>Standard C++ library: standard library exception types · 58</p><p>standard template library: set class example · 475</p><p><strong>stdio</strong> · 176</p><p>STDIO.H · 195</p><p>stream · 182; output formatting · 214</p><p>streambuf · 201; and get( ) · 202</p><p>streampos, moving · 203</p><p>string: Standard C++ library string class · 182; transforming character strings to typed values · 209</p><p>stringizing, preprocessor · 222</p><p>strstream · 207</p><p>structural design patterns · 672</p><p>subobject: duplicate subobjects in multiple inheritance · 635</p><p>subtasks · 719</p><p>synchronization: (concurrency) example of problem from lack of synchronization · 762; and blocking · 765</p><p>synchronization, thread · 748</p><p>Synchronization_Exception (Concurrency) · 731</p><p>Synchronization_Exception, in ZThread library · 727</p><p>synchronized: threading, wrapper for an entire class · 753</p><p>SynchronousExecutor (Concurrency) · 733</p><p>T</p><p>task: defining for threading · 724</p><p>tellg( ) · 204</p><p>tellp( ) · 204</p><p>template: and run-time type identification · 610; function templates · 279</p><p>temporary: object · 234</p><p>terminate( ) · 46, 65; uncaught exceptions · 45</p><p>terminating threads · 765</p><p>termination: vs. resumption, exception handling · 41</p><p>termination problem, concurrency · 757</p><p>thread · 719; atomic operation · 763; blocked · 764; blocking and mutexes · 767; broadcast( ) · 765, 773, 787; busy wait · 762, 773; Cancelable class from ZThread libaray · 746; colliding over resources, improperly accessing shared resources · 744; Condition class for wait() and signal() · 772; cooperation · 771; dead state · 764; deadlock · 750, 795; deadlock, and priorities · 738; dining philosophers · 795; drawbacks · 803; example of problem from lack of synchronization · 762; getPriority( ) · 739; handshaking between tasks · 772; I/O and threads, blocking · 767; interrupt( ) · 765; interrupted status · 769; Interrupted_Exception · 769; iostreams and colliding output · 757; memory management · 740; multiple, for problem-solving · 772; mutex, for handshaking · 772; mutex, simplifying with the Guard template · 750; new state · 764; order of task shutdown · 746; order of thread execution · 737; priority · 738; producer-consumer · 777; queues solve problems · 781; race condition · 746; reference counting · 741; reference-counting with CountedPtr · 743; runnable state · 764; serialization · 781; setPriority( ) · 740; sharing resources · 740; signal( ) · 764, 772; sleep( ) · 736, 764; states · 764; synchronization · 748; synchronization and blocking · 765; synchronized wrapper for an entire class · 753; termination · 765; termination problem · 757; thread local storage · 754; threads and efficiency · 721; TQueue, solving threading problems with · 781; wait( ) · 764, 772; when to use threads · 803; yield( ) · 734; ZThread FastMutex · 761</p><p>thread object, concurrency · 726</p><p>thread, and concurrency · 719</p><p>ThreadedExecutor (Concurrency) · 731</p><p>throughput, optimize · 720</p><p>throw · 37, 38</p><p>throwing an exception · 37</p><p>TQueue, solving threading problems with · 781</p><p>transforming character strings to typed values · 209</p><p>try · 38; Function-level try blocks · 56</p><p>try block · 38; function-level · 56</p><p>type: automatic type conversions and exception handling · 42; run-time type identification (RTTI) · 599</p><p>typeid( ): difference between dynamic_cast and typeid( ), run-time type identification · 609</p><p>typeinfo: structure · 619</p><p>U</p><p>ULONG_MAX · 234</p><p>uncaught exceptions · 45</p><p>uncaught_exception( ) · 75</p><p>unexpected( ) · 63</p><p>Unix · 234</p><p>Urlocker, Zack · 660</p><p>user interface: responsive, with threading · 720, 728</p><p>V</p><p>value: transforming character strings to typed values · 209</p><p>Van Rossum, Guido · 804</p><p>variable: variable argument list · 181</p><p>vector of change · 664</p><p>virtual: simulating virtual constructors · 691; virtual functions inside constructors · 692</p><p>visitor pattern · 714</p><p>void: void pointers and run-time type identification · 609</p><p>VPTR · 692</p><p>VTABLE · 692; and run-time type identification · 619</p><p>W</p><p>wait( ), threading · 764, 772</p><p>web servers, multiprocessor · 721</p><p>wrapping, class · 176</p><p>write( ) · 191</p><p>ws · 225</p><p>Y</p><p>yield( ), threading · 734</p><p>Z</p><p>ZThread: Cancelable class · 746; Executors · 731; installing the library · 723; multithreading library for C++ · 722</p></section></section></body><body name="notes"><title><p>Notes</p></title><section id="n1"><title><p>1</p></title><p>You might be surprised when you run the example—some C++ compilers have extended <strong>longjmp( )</strong> to clean up objects on the stack. This behavior is not portable.</p></section><section id="n2"><title><p>2</p></title><p>Visual Basic supports a limited form of resumptive exception handling with its ON ERROR facility.</p></section><section id="n3"><title><p>3</p></title><p>In fact, you might want to always specify exception objects by <strong>const</strong> reference in exception handlers. It’s very rare to modify and rethrow an exception. We are not dogmatic about this practice however.</p></section><section id="n4"><title><p>4</p></title><p> Only <emphasis>unambiguous, accessible base classes</emphasis> can catch derived exceptions. This rule minimizes the runtime overhead needed to validate exceptions. Remember that exceptions are checked at runtime, not at compile time, and therefore the extensive information available at compile time is not available during exception handling</p></section><section id="n5"><title><p>5</p></title><p> For more detail on <strong>auto_ptr</strong>, see Herb Sutter’s article entitled, "Using auto_ptr Effectively" in the October 1999 issue of the <emphasis>C/C++ Users Journal</emphasis>, pp. 63–67.</p></section><section id="n6"><title><p>6</p></title><p>If you’re interested in a more in-depth analysis of exception safety issues, the definitive reference is Herb Sutter’s <emphasis>Exceptional C++</emphasis>, Addison-Wesley, 2000.</p></section><section id="n7"><title><p>7</p></title><p>The library function <strong>uncaught_exception( )</strong> returns <strong>true</strong> in the middle of stack unwinding, so technically you can test <strong>uncaught_exception( )</strong> for <strong>false</strong> and let an exception escape from a destructor. We’ve never seen a situation in which this constituted good design, however, so we only mention it in this footnote.</p></section><section id="n8"><title><p>8</p></title><p>Some compilers do throw exceptions in these cases, but they usually provide a compiler option to disable this (unusual) behavior.</p></section><section id="n9"><title><p>9</p></title><p>This depends, of course, on how much checking of return codes you would have to insert if you weren’t using exceptions.</p></section><section id="n10"><title><p>10</p></title><p>Borland enables exceptions by default; to disable exceptions use the <strong>-x</strong>- compiler option. Microsoft disables support by default; to turn it on, use the <strong>-GX</strong> option. With both compilers use the <strong>-c</strong> option to compile only.</p></section><section id="n11"><title><p>11</p></title><p>The GNU C++ compiler uses the zero-cost model by default. Metrowerks Code Warrior for C++ also has an option to use the zero-cost model.</p></section><section id="n12"><title><p>12</p></title><p>Thanks to Scott Meyers and Josee Lajoie for their insights on the zero-cost model. You can find more information on how exceptions work in Josee’s excellent article, "Exception Handling: Behind the Scenes," <emphasis>C++ Gems</emphasis>, SIGS, 1996.</p></section><section id="n13"><title><p>13</p></title><p>Among other things he invented Quicksort.</p></section><section id="n14"><title><p>14</p></title><p>As quoted in <emphasis>Programming Language Pragmatics</emphasis>, by Michael L. Scott, Morgan-Kaufmann, 2000.</p></section><section id="n15"><title><p>15</p></title><p>See his book, <emphasis>Object-Oriented Software Construction</emphasis>, Prentice-Hall, 1994.</p></section><section id="n16"><title><p>16</p></title><p>This is still an assertion <emphasis>conceptually</emphasis>, but since we donвЂ™t want to halt execution, the <strong>assert(В )</strong> macro is not appropriate. Java 1.4, for example, throws an exception when an assertion fails.</p></section><section id="n17"><title><p>17</p></title><p>There is a nice phrase to help remember this phenomenon: вЂњRequire no more; promise no less,вЂќ first coined in <emphasis>C++ FAQs</emphasis>, by Marshall Cline and Greg Lomow (Addison-Wesley, 1994). Since pre-conditions can weaken in derived classes, we say that they are <emphasis>contravariant</emphasis>, and, conversely, post-conditions are <emphasis>covariant</emphasis> (which explains why we mentioned the covariance of exception specifications in Chapter 1).</p></section><section id="n18"><title><p>18</p></title><p>This section is based on ChuckвЂ™s article, вЂњThe Simplest Automated Unit Test Framework That Could Possibly WorkвЂќ, C/C++ Users Journal, Sept. 2000.</p></section><section id="n19"><title><p>19</p></title><p>A good book on this subject is Martin Fowler's <emphasis>Refactoring: Improving the Design of Existing Code</emphasis> (Addison-Wesley, 2000). See also <a l:href="http://www.refactoring.com/">www.refactoring.com</a>. Refactoring is a crucial practice of Extreme Programming (XP).</p></section><section id="n20"><title><p>20</p></title><p>Lightweight methodologies such as XP have вЂњjoined forcesвЂќ in the Agile Alliance (see http://www.agilealliance.org/home).</p></section><section id="n21"><title><p>21</p></title><p>Our Date class is also вЂњinternationalizedвЂќ, in that it supports wide character sets. This is introduced at the end of the next chapter.</p></section><section id="n22"><title><p>22</p></title><p>See <a l:href="http://sourceforge.net/projects/cppunit">http://sourceforge.net/projects/cppunit</a> for more information.</p></section><section id="n23"><title><p>23</p></title><p>вЂњRuntime Type IdentificationвЂќ, discussed in chapter 9. Specifically, we use the <strong>name(В )</strong> member function of the <strong>typeinfo</strong> class. By the way, if you're using Microsoft Visual C++, you need to specify the compile option <strong>/GR</strong>. If you don't, you'll get an access violation at runtime.</p></section><section id="n24"><title><p>24</p></title><p>In particular, we use <emphasis>stringizing</emphasis> (via the <strong>#</strong> operator) and the predefined macros <strong>__FILE</strong>__ and <strong>__LINE__</strong>. See the code later in the chapter.</p></section><section id="n25"><title><p>25</p></title><p>Batch files and shell scripts work well for this, of course. The <strong>Suite</strong> class is a C++-based way of organizing related tests.</p></section><section id="n26"><title><p>26</p></title><p>Our key technical reviewer, Pete Becker of Dinkumware. Ltd., brought to our attention that it is illegal to use macros to replace C++ keywords. His take on this technique was as follows: вЂњ"This is a dirty trick. Dirty tricks are sometimes necessary to figure out why code isn't working, so you may want to keep this in your toolbox, but don't ship any code with it." Caveat programmer :-).</p></section><section id="n27"><title><p>27</p></title><p>Thanks to Reg Charney of the C++ Standards Committee for suggesting this trick.</p></section><section id="n28"><title><p>28</p></title><p>Some of the material in this chapter was originally created by Nancy Nicolaisen.</p></section><section id="n29"><title><p>29</p></title><p>ItвЂ™s difficult to make reference-counting implementations thread safe. (See Herb Sutter, <emphasis>More Exceptional C++</emphasis>, pp. 104вЂ"14). See Chapter 10 for more on programming with multiple threads.</p></section><section id="n30"><title><p>30</p></title><p>It as an abbreviation for вЂњno position.вЂќ</p></section><section id="n31"><title><p>31</p></title><p>Discussed in depth in Chapter 6.</p></section><section id="n32"><title><p>32</p></title><p>To keep the exposition simple, this version does not handle nested tags, such as comments.</p></section><section id="n33"><title><p>33</p></title><p>It is tempting to use mathematics here to factor out some of these calls to <strong>erase(В )</strong>, but since in some cases one of the operands is <strong>string::npos</strong> (the largest unsigned integer available), integer overflow occurs and wrecks the algorithm.</p></section><section id="n34"><title><p>34</p></title><p>Alert: For the safety reasons mentioned, the C++ Standards Committee is considering a proposal to redefine <strong>string::operator[]</strong> to behave identically to <strong>string::at()</strong> for C++0x.</p></section><section id="n35"><title><p>35</p></title><p>Your implementation can define all three template arguments here. Because the last two template parameters have default arguments, such a declaration is equivalent to what we show here.</p></section><section id="n36"><title><p>36</p></title><p>Beware that some versions of Microsoft Word erroneously replace single quote characters with an extended ASCII character when you save a document as text, which of course causes a compile error. We have no idea why this happens. Just replace the character manually with an apostrophe.</p></section><section id="n37"><title><p>37</p></title><p>POSIX, an IEEE standard, stands for вЂњPortable Operating System InterfaceвЂќ and is a generalization of many of the low-level system calls found in UNIX systems.</p></section><section id="n38"><title><p>38</p></title><p>The implementation and test files for FULLWRAP are available in the freely distributed source code for this book. See the preface for details.</p></section><section id="n39"><title><p>39</p></title><p>Explained in depth in Chapter 5.</p></section><section id="n40"><title><p>40</p></title><p>For this reason, we can write <strong>ios::failbit</strong> instead of <strong>ios_base::failbit</strong> to save typing.</p></section><section id="n41"><title><p>41</p></title><p>It is customary to use <strong>operator void*(В )</strong> in preference to <strong>operator bool(В )</strong> because the implicit conversions from <strong>bool</strong> to <strong>int</strong> may cause surprises, should you errantly place a stream in a context where an integer conversion can be applied. The <strong>operator void*(В )</strong> function will only implicitly be called in the body of a Boolean expression.</p></section><section id="n42"><title><p>42</p></title><p>An integral type used to hold single-bit flags.</p></section><section id="n43"><title><p>43</p></title><p>A more in-depth treatment of stream buffers and streams in general can be found in Langer &amp; KreftвЂ™s, <emphasis>Standard C++ IOStreams and Locales</emphasis>, Addison-Wesley, 1999.</p></section><section id="n44"><title><p>44</p></title><p>For more information on machine epsilon and floating-point computation in general, see ChuckвЂ™s article, вЂњThe Standard C Library, Part 3вЂќ, <emphasis>C/C++ Users Journal</emphasis>, March 1995, also available at www.freshsources.com/1995006a.htm.</p></section><section id="n45"><title><p>45</p></title><p>Before putting <strong>nl</strong> into a header file, make it an <strong>inline</strong> function (see Chapter 7).</p></section><section id="n46"><title><p>46</p></title><p>Jerry Schwarz is the designer of iostreams.</p></section><section id="n47"><title><p>47</p></title><p>See the Langer &amp; Kreft book mentioned earlier for more detailed information.</p></section><section id="n48"><title><p>48</p></title><p>See, for example, DinkumwareвЂ™s Abridged library at www.dinkumware.com. This library omits locale support. and exception support is optional. </p></section><section id="n49"><title><p>49</p></title><p>Vandevoorde and Josuttis, <emphasis>C++ Templates: The Complete Guide</emphasis>, Addison-Wesley, 2003.</p></section><section id="n50"><title><p>50</p></title><p>The C++ standards committee is considering relaxing the only-within-a-template rule for these disambiguation hints, and some compilers are allowing then in non-template code already.</p></section><section id="n51"><title><p>51</p></title><p>See Stroustrup, <emphasis>The C++ Programming Language</emphasis>, 3<sup>rd</sup> Edition, Addison-Wesley, pp. 335-336.</p></section><section id="n52"><title><p>52</p></title><p>Technically, comparing two pointers not inside the same array is undefined behavior, but compilers nowadays donвЂ™t complain about this. All the more reason to do it right.</p></section><section id="n53"><title><p>53</p></title><p>We are indebted to Nathan Myers for this example.</p></section><section id="n54"><title><p>54</p></title><p>Such as type information encoded in a decorated name.</p></section><section id="n55"><title><p>55</p></title><p>C++ compilers can introduce names anywhere they want, however. Fortunately, most donвЂ™t declare names they donвЂ™t need.</p></section><section id="n56"><title><p>56</p></title><p>If youвЂ™re interested in seeing the proposal, itвЂ™s Core Issue 352.</p></section><section id="n57"><title><p>57</p></title><p>A reference to the British animated short feature <emphasis>The Wrong Trousers</emphasis> by Nick Park.</p></section><section id="n58"><title><p>58</p></title><p>We discuss <strong>vector&lt;bool&gt;</strong> in depth in Chapter 7.</p></section><section id="n59"><title><p>59</p></title><p>Since the forwarding functions are inline, no code is generated at all!</p></section><section id="n60"><title><p>60</p></title><p>Also called <emphasis>Koenig lookup</emphasis>, after Andrew Koenig, who first proposed the technique to the C++ standards committee. ADL applies universally, whether templates are involved or not.</p></section><section id="n61"><title><p>61</p></title><p>In a talk given at <emphasis>The C++ Seminar</emphasis>, Portland, OR, September, 2001.</p></section><section id="n62"><title><p>62</p></title><p>Another template idiom, mixin inheritance, is covered in Chapter 9.</p></section><section id="n63"><title><p>63</p></title><p>The fact that <strong>char_traits&lt;&gt;::compare(В )</strong> may call <strong>strcmp(В )</strong> in one instance vs. <strong>wcscmp(В )</strong> in another, for example, is immaterial to the point we make here: the function performed by <strong>compare(В )</strong> is the same.</p></section><section id="n64"><title><p>64</p></title><p><emphasis>Modern C++ Design: Generic Programming and Design Patterns Applied</emphasis>, Addison-Wesley, 2001.</p></section><section id="n65"><title><p>65</p></title><p><emphasis>C++ Gems</emphasis>, edited by Stan Lippman, SIGS, 1996.</p></section><section id="n66"><title><p>66</p></title><p>Floating-point values are not compile-time constants, and therefore cannot be used in compile-time arithmetic.</p></section><section id="n67"><title><p>67</p></title><p>In 1966 BГ¶hm and Jacopini proved that any language supporting selection and repetition, along with the ability to use an arbitrary number of variables, is equivalent to a Turing machine, which can implement any algorithm.</p></section><section id="n68"><title><p>68</p></title><p>Czarnecki and Eisenecker, <emphasis>Generative Programming: Methods, Tools, and Applications</emphasis>, Addison-Wesley, 2000, p. 417.</p></section><section id="n69"><title><p>69</p></title><p>There is a much better to compute powers of integers, of course (viz., the Russian Peasant Algorithm), but that is beside the point here.</p></section><section id="n70"><title><p>70</p></title><p><emphasis>Modern C++ Design</emphasis>, pp. 23-26.</p></section><section id="n71"><title><p>71</p></title><p>You actually are not allowed to pass object types (other than built-ins) to an ellipsis parameter specification, but since we are only asking for its size (a compile-time operation), the expression is never actually evaluated at runtime.</p></section><section id="n72"><title><p>72</p></title><p>A reprint of ToddвЂ™s original article can be found in Lippman, <emphasis>C++ Gems</emphasis>, SIGS, 1996.</p></section><section id="n73"><title><p>73</p></title><p>See his and NicoвЂ™s book, <emphasis>C++ Templates</emphasis>, book cited earlier.</p></section><section id="n74"><title><p>74</p></title><p>Namely, Blitz++ (<a l:href="http://www.oonumerics.org/blitz/">http://www.oonumerics.org/blitz/</a>), the Matrix Template Library (<a l:href="http://www.osl.iu.edu/research/mtl/">http://www.osl.iu.edu/research/mtl/</a>), and POOMA (<a l:href="http://www.acl.lanl.gov/pooma/">http://www.acl.lanl.gov/pooma/</a>).В  </p></section><section id="n75"><title><p>75</p></title><p>We mean вЂњvectorвЂќ in the mathematical sense, as a fixed-length, one-dimensional, numerical array.</p></section><section id="n76"><title><p>76</p></title><p>Langer and Kreft, вЂњC++ Expression TemplatesвЂќ, <emphasis>C/C++ Users Journal</emphasis>, March 2003. See also the article on expression templates by Thomas Becker in the June 2003 issue of the same journal, and which was the inspiration for the material in this section.</p></section><section id="n77"><title><p>77</p></title><p>As explained earlier, you must explicitly instantiate a template only once per program.</p></section><section id="n78"><title><p>78</p></title><p>Visit http://www.bdsoft.com/tools/stlfilt.html.</p></section><section id="n79"><title><p>79</p></title><p>Or something that is callable as a function, as youвЂ™ll see shortly.</p></section><section id="n80"><title><p>80</p></title><p>This is simply an English rendition of <strong>O(n log n)</strong>, which is the mathematical way of saying that for large <strong>n</strong>, the number of comparisons grows in direct proportion to the function <strong>f(n) = n log n</strong>.</p></section><section id="n81"><title><p>81</p></title><p>Unless you do something ungainly like use global variables.</p></section><section id="n82"><title><p>82</p></title><p>Function objects are also called <emphasis>functors</emphasis>, after a mathematical concept with similar behavior.</p></section><section id="n83"><title><p>83</p></title><p>All standard iterators define a number of nested types, including <strong>value_type</strong>, which represents the type the iterator refers to. See Chapter 7 for more detail.</p></section><section id="n84"><title><p>84</p></title><p>If a compiler were to define <strong>string::empty</strong> with default arguments (which is allowed), then the expression <strong>&amp;string::empty</strong> would define a pointer to a member function taking the total number of arguments. Since there is no way for the compiler to provide the extra defaults, there would be a вЂњmissing argumentвЂќ error when an algorithm applied <strong>string::empty</strong> via <strong>mem_fun_ref</strong>.</p></section><section id="n85"><title><p>85</p></title><p>STLPort, for instance, which comes with version 6 of Borland C++ Builder and is based on SGI STL.</p></section><section id="n86"><title><p>86</p></title><p>The <strong>stable_sort(В )</strong> algorithm uses <emphasis>mergesort</emphasis>, which is indeed stable, but tends to run slower than <emphasis>quicksort</emphasis> on average.</p></section><section id="n87"><title><p>87</p></title><p>Iterators are discussed in more depth in the next chapter.</p></section><section id="n88"><title><p>88</p></title><p>Algorithms can determine the type of an iterator by reading its <strong>tag</strong>, discussed in the next chapter.</p></section><section id="n89"><title><p>89</p></title><p>WeвЂ™re ignoring the copy constructor and assignment operator in this example, since they donвЂ™t apply.</p></section><section id="n90"><title><p>90</p></title><p>Without violating any copyright laws, of course.</p></section><section id="n91"><title><p>91</p></title><p>Visit <a l:href="http://www.dinkumware.com/">http://www.dinkumware.com</a>, http://www.sgi.com/tech/stl, or http://www.stlport.org.</p></section><section id="n92"><title><p>92</p></title><p>The container adaptors, stack, queue, and priority_queue do not support iterators, since they do not behave as sequences from the userвЂ™s point of view.</p></section><section id="n93"><title><p>93</p></title><p>It will only work for implementations of vector that uses a <emphasis>pointer</emphasis> (a <strong>T*</strong>) as the iterator type, like STLPort does.</p></section><section id="n94"><title><p>94</p></title><p>These were actually created to abstract the вЂњlocaleвЂќ facets away from iostreams, so that locale facets could operate on any sequence of characters, not only iostreams. Locales allow iostreams to easily handle culturally-different formatting (such as the representation of money) and are beyond the scope of this book.</p></section><section id="n95"><title><p>95</p></title><p>You will need to provide a <strong>char_traits</strong> specialization for any other argument type.</p></section><section id="n96"><title><p>96</p></title><p>We are indebted to Nathan Myers for explaining this.</p></section><section id="n97"><title><p>97</p></title><p>This is another example coached by Nathan Myers.</p></section><section id="n98"><title><p>98</p></title><p>For a detailed explanation of this oddity, see Items 6 and 29 in Scott MeyerвЂ™s <emphasis>Effective STL</emphasis>.</p></section><section id="n99"><title><p>99</p></title><p>We revisit multi-threading issues in Chapter 11.</p></section><section id="n100"><title><p>100</p></title><p>Chuck designed and provided the original reference implementations for <strong>bitset</strong> and also <strong>bitstring</strong>, the precursor to <strong>vector&lt;bool&gt;</strong>, while an active member of the C++ standards committee in the early 1990s.</p></section><section id="n101"><title><p>101</p></title><p>They will likely appear in the next revision of Standard C++.</p></section><section id="n102"><title><p>102</p></title><p>Available at http://www.sgi.com/tech/stl.</p></section><section id="n103"><title><p>103</p></title><p>As we explained earlier, the <strong>vector&lt;bool&gt;</strong> specialization is also a non-STL container to some degree.</p></section><section id="n104"><title><p>104</p></title><p>With MicrosoftвЂ™s compilers you will have to enable RTTI; itвЂ™s disabled by default. The command-line option enable it is <strong>/GR</strong>.</p></section><section id="n105"><title><p>105</p></title><p>Compilers typically insert a pointer to a classвЂ™s RTTI table inside of its virtual function table.</p></section><section id="n106"><title><p>106</p></title><p>A <strong>dynamic_cast&lt;void*&gt;</strong> always gives the address of the full objectвЂ"not a subobject. This will be explained more fully in the next chapter.</p></section><section id="n107"><title><p>107</p></title><p>Even more importantly, we donвЂ™t want undefined behavior. It is an error for a base class not to have a virtual destructor.</p></section><section id="n108"><title><p>108</p></title><p>The actual layout is of course implementation specific.</p></section><section id="n109"><title><p>109</p></title><p>But not detected as an error.В  <strong>dynamic_cast</strong>, however can solve this problem. See the next chapter for details.</p></section><section id="n110"><title><p>110</p></title><p>Compilers can add arbitrary padding, so the size of an object must be at least as large as the sum of its parts, but can be larger.</p></section><section id="n111"><title><p>111</p></title><p>We use the term <emphasis>hierarchy</emphasis> because everyone else does, but the graph representing multiple inheritance relationships is in general a <emphasis>directed acyclic graph</emphasis> (DAG), also called a <emphasis>lattice</emphasis>, for obvious reasons.</p></section><section id="n112"><title><p>112</p></title><p>The presence of these pointers explains why the size of <strong>b</strong> is much larger than the size of four integers.В  This is (part of) the cost of virtual base classes. There is also VPTR overhead due to the virtual constructor.</p></section><section id="n113"><title><p>113</p></title><p>Note that the virtual inheritance is crucial to this example. If <strong>Top</strong> were not a virtual base class, there would be multiple <strong>Top</strong> subobjects, and the ambiguity would remain. Dominance with multiple inheritance only comes into play with virtual base classes.</p></section><section id="n114"><title><p>114</p></title><p>Jerry Schwarz, the author of IOStreams, has remarked to both of us on separate occasions that if he had it to do over again, he would probably remove MI from the design of IOStreams and use multiple stream buffers and conversion operators instead.</p></section><section id="n115"><title><p>115</p></title><p>A phrase coined by Zack Urlocker.</p></section><section id="n116"><title><p>116</p></title><p>Also known as the вЂњGang of FourвЂќ book (GoF). Conveniently, the examples are in C++.</p></section><section id="n117"><title><p>117</p></title><p>The C++ standards states: вЂњNo translation unit shall contain more than one definition of any variable, function, class type, enumeration type or templateвЂ¦ Every program shall contain exactly one definition of every non-inline function or object that is used in that program.вЂќ</p></section><section id="n118"><title><p>118</p></title><p>This is known as MeyersвЂ™ Singleton, after its creator, Scott Meyers.</p></section><section id="n119"><title><p>119</p></title><p>Andrei Alexandrescu develops a superior, policy-based solution to implementing the Singleton pattern in <emphasis>Modern C++ Design</emphasis>.</p></section><section id="n120"><title><p>120</p></title><p>For more information, see the article вЂњOnce is Not EnoughвЂќ by Hyslop and Sutter in the March 2003 issue of <emphasis>CUJ</emphasis>.</p></section><section id="n121"><title><p>121</p></title><p>For up-to-date information, visit http://hillside.net/patterns.</p></section><section id="n122"><title><p>122</p></title><p>James O. Coplien, <emphasis>Advanced C++ Programming Styles and Idioms</emphasis>, Addison-Wesley, 1992.</p></section><section id="n123"><title><p>123</p></title><p>It differs from Java in that <strong>java.util.Observable.notifyObservers(В )</strong> doesn't call <strong>clearChanged(В )</strong> until after notifying all the observers</p></section><section id="n124"><title><p>124</p></title><p>There is some similarity between inner classes and <emphasis>subroutine closures</emphasis>, which save the reference environment of a function call so it can be reproduced later.</p></section><section id="n125"><title><p>125</p></title><p>Much of this chapter began as a translation from the <emphasis>Concurrency </emphasis>chapter in <emphasis>Thinking in Java, 3</emphasis><sup><emphasis>rd</emphasis></sup><emphasis> edition</emphasis>, Prentice Hall 2003.</p></section><section id="n126"><title><p>126</p></title><p>This is an oversimplification. Sometimes even when it seems like an atomic operation should be safe, it may not be, so you must be very careful when deciding that you can get away without synchronization. Removing synchronization is often a sign of premature optimization вЂ" things that can cause you a lot of trouble without gaining much. Or anything.</p></section><section id="n127"><title><p>127</p></title><p>This is in contrast to Java, where you must hold the lock in order to call <strong>notify()</strong> (JavaвЂ™s version of <strong>signal()</strong>). Although Posix threads, on which the ZThread library is loosely based, do not require that you hold the lock in order to call <strong>signal()</strong> or <strong>broadcast()</strong>, it is often recommended.</p></section><section id="n128"><title><p>128</p></title><p>At the time of this writing, Cygwin (www.cygwin.com) was undergoing much-needed changes and improvements to its threading support, but we were still unable to observe deadlocking behavior with this program under the available version of Cygwin. The program deadlocked quickly under, for example, Linux.</p></section></body><binary id="cover" content-type="image/jpeg">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</binary>
<binary id="1" content-type="image/gif">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</binary>
<binary id="2" content-type="image/gif">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</binary>
<binary id="3" content-type="image/gif">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</binary>
<binary id="4" content-type="image/gif">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</binary>
<binary id="5" content-type="image/png">iVBORw0KGgoAAAANSUhEUgAAAI8AAABLCAYAAABJGtQxAAAACXBIWXMAAAPoAAAD6AG1e1JrAAACeUlEQVR4nO2bC44jIQxEc/9L12qljbSKoAMFBkPek6KeYfg1FDZhzOsFAAAAADvRvw9AF4gGQoST1SIpab9+CjX+LdNEqfIzLEYd6RkmSo1psADEA2nE87kXmb03kdkvOMTyqPIs5Xv6zO4XHCKeqE2tGtPgErc1EzWmwaHiaS2D2zqcmec8NeFEWh9NrhsWnDCX0ku/R02uEM5+RiaXVf/juAJAOIAIwAcLAjaIB2wQD9ggHrBBPGCDeMAG8YAN4gEbxAM2iAdsEM+FrAo5aAnJyIJ2d+AEooKontoqpWeJmVGivqRn5SBheS5itXAQzwW03FmKaK8lX29dUe+ggDqvwhmg3lsIPW1kuOj3BvEc5LLe+Zz6sDyLWb2yZq32FcL5C5YnKBg9yhVkuOj3BvEkG5jZ4oo8o1JAnVfw7WLdDlfwaRF2XvQTB4XPg7Nj0HrrZfUnoHWDudPyjOSFQFosyor/cSGIS3naa8xuA6AbxAM2iAdsEA/YIB6wQTxgg3jABvGADeIBG8QD22KIsqGk/epFN8dMu2Uj0cfzRI4KPRkRTwQjdet1D0e8S7Z4nhE3mpHb3mfodkS0SXXErIWmvhTs3xKqm22RTiHbS52wUlV5tpTryZue3ZGE325TOLc3dlifkfK1POnZLZ4ZbSigH1HCKdVRy5OeFeKJNtcyyvxfdmQMesv+pNtS0nZk9KVU1nGPrXuen98wlwauZ8O4SjwyDwuf6unJ863eqw4KRyY1w6ZWlbRRd1RLg4YBajHppa+stW9KsyZCk/tVqwfhdE5Gz+p1zjhmoKB+IZaBCXHLtPr9VT5cZr8Qz+CgM4AAAAAA8NrJHwg/xEqYrQ2NAAAAAElFTkSuQmCC</binary>
<binary id="6" content-type="image/gif">R0lGODlhpAH6AHcAMSH+GlNvZnR3YXJlOiBNaWNyb3NvZnQgT2ZmaWNlACH5BAEAAAAALAEAAQCiAfkAhAAAAAAAAE1NTXx8fGhoaIyMjJqamqenp7Kysr29vdDQ0MfHx9nZ2enp6eHh4fDw8P///wECAwECAwECAwECAwECAwECAwECAwECAwECAwECAwECAwECAwECAwECAwECAwX/ICCOZGmeaKqubOu+cOwGdG3feK7vfO/nsqBwSCwaj8ikcskcBiDQqHRKrVqv2Kx2Gmh6v+CweEwuy57btHrNrnbN8Lh8Tq830e28fh992/+AgYKDYHh8h4hZfoSMjY6PjYaJk5QQi5CYmZqbS5KVn3uXnKOkpaYjnqCqa6Knrq+wgKmrtIqxt7i5ZbO1vVStusHCwzC8vseWxMrLzCfGyL3AzdPUr8/QtNLV29yZ19iq2t3j5IHf4J/i5evsZufolOrt8/RM7/CJ8vX7/EL3UA0G0BjQYBINKA4KxOvHsKGRfxAIBGjQIAABUAcNOtzI8QVEGgWnHKBhAMKDAhZD/2Y8OFDgkxsFKw7Qo6+jzX4QEQQQcCAkhJEUAxQwMNEilJUvAziwhIaGggAIIOhUQPOm1asQITg4ICBAgqM5uDRNCrasgIsEBIS6yrZj1j5jpWSEWxZp2QQBnh5Y27YvQ4gSg16EQHRBxaFFB3dtwIBlXKYmazzg67cyPYgBB/ocKRRCA5QEQiroqpMsZAijAywYqZCy5dfl3iJDudQ17NvbZEezSJVPTdzAb+nGx+Z38OOnhhNXYxy5c07Kl29p/rw6pOjSbVnfDgt79ivUuYuX9b1W+PHo53gv/yu9e2/sV51/Tz/M+vh96usfdB9/sv0A2tEffvMFaCARA8ZX4P+BDMaQIHsLNighCw+WF+GEGDrjXzoZdqjEDyCGKOKIPHhoYikXnqhiMF2kuOKL3QHgIow0oihjjThy48eMOfYYCSo+BknMjkIWmcslPBqppDs4LOmkK0k+KeUYUU5ppRdVXqllEllu6SWCX4bJn5hk/tFlmWimcGaabJKwZpttvglnmnLOWWaddoqJZ55f7snnln7+eWWggk5JaKFPHorokoouamSjjgoJaaQ+TkppjpZeWmOmmsLIaacrfgrqiaKO6mGppmaIaqoTrspqg66+emCssgZIa6373Yprfbru+l6vd5Io7LDEFmvsscgmq+yyzDZbLDPA8hPtPtMWU+n/tctUexm2ymg7j7ftgEshtziKu4K5sZE7DLrksDuOu86oSyO8JtCbm7ws4vuivW7qGyq0/qrIL5A9DjyNwTcWHPAdzjZMbLYORzwixBJX7MOGlRhc4XcaY2zQxtl17HE+2Y6MyFwm28ZiyoeIzHIeKL9cXMkyw0xzzayALJ3LODN3c8/T6bwcz0BrQXTR4AlN3NFIW8F002JBbfTPUrtBddVyKY3P01j/N2TXbmgND9dYky11zGAfdXXaZkONNttrg91202/LHXfXcyNdN953l9332WKjk7fef7sdXWYBEIRQa2nsrbIuxjjeRkKTUD51tx/TIEBvMHsneRqBVTTY/+dZY9Q36cxhR/rgijSlFk2eRwdS1hlxtpdJoKn0hF4aYZ40WDptzvtIVHFWEgQMuIRSDUwJJEACRG3+E0nA7/QU89p9nc8TD3QGhe3VS++ZRKXFE13wPdE1vQK8EyU6WLz3rr3TYzFQkQDdoxXAA0AdBkFXD5AJUhjQvQAQcCf96wwN7LeT02RvXZmzyGTWx7sF3g8KtHEA6oJWOa54pSyncYxYaLCAhfiOfiA8iEQ0eBEcQEB5JbRLCMNil9UVrnFPeN8Md8jD7aXjMTWUBA24MhiSnTBsKXyCTlCyF7Q5AAESkQgQxxKzIE7nhhzkoQi1GLtEhM4opyFe+xJTlv+R1OZkp5si8mrAAMKoxn8CKchOZIiUwvjPipebX8u4l7jv5aWCjyEKAxrTRUQgTnGo6UoJweeZ3JWlMbdD4xF/oUam4IEzrXkAURLXgNQsgI5PwGQSE6maBwpDdTUITRQYKcMGkG+DRgscOFgHNFriDJa1xCLhJsk2WWLDlrfUZS19CQ1g1syYL8Nlz5CZTGEuk5jIYCbLpGkyZQaTl3DDJt6geQxqVtOZt+SmL7w5MnJizJrHBOc19Zg2B7ZTbdrkWzyrhk6ZmfOc6rSnOKORT3v2c5r7NM8/pznQagY0GwX95jwB9065JLScDz3nQeUTUXwu1HANzc9F3VZR/1j/7KM9oBhIR1oDkZIUpKZCmK/80qKVCqqlLuUTTGM6JyLRFE42vSmbcqrTO5VApT39S5OCSiei4tSocULqTpVaVKb61KlkAipUqTVVPVU1TFK9ari06qWscjVdXx1UWMU6VkOV1axnTVRa1bpWRrXVrW99VFzlOldJ1dWud11YXk3k1b3my6/lAmxgBTsvwhbWsPtCbGIVKzDGNtaxfIVsZCXbob5SdhSWvewmMqtZb3S2VZ+VEGdD64jRkpYRpj3tmFRrK9a21rW5gm1sZXuZk56UtqXNKDxxS4iJhoO3qNWt14BrDuGm9qu+NR1xBZFcDi23uLo9Llebm7HnQjej+9LVKnVNaF0BGbe7ZvoueOuwXfmNVw7lNeJ50Sve9cYBlRPxDPamYDkkcte97shcCT/5tr3V02r4hQMqCaCQAkjRjwHY5EFcaT0QmjfAVPqYTixRvgQuDwqqbKA7JQlhMqCyMXghpCVvAIUHIMAlDlZvh8WASktCBmUZWaEMH7ziL7QYJQo5iB2FgpSKPIbGNb7DxyCAl6/UjgYK8aReZqziIGOpvU5+cnSjXAgoU7kTVr4yl7Ks5SOkl8Nd3vKUw/whLpPZCWY+cxC+3DI1I4HNvnGzl9MsZ4/Quc4tgPPj8GznMfN5zXf+s5oCLWhn2JakhT7DoUfqoxAAADs=</binary>
<binary id="7" content-type="image/gif">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</binary>
<binary id="8" content-type="image/gif">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</binary>
<binary id="9" content-type="image/gif">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</binary>
<binary id="10" content-type="image/gif">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</binary>
<binary id="11" content-type="image/gif">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</binary>
<binary id="12" content-type="image/gif">R0lGODlhqgDzAHcAMSH+GlNvZnR3YXJlOiBNaWNyb3NvZnQgT2ZmaWNlACH5BAEAAAAALAIAAgCnAPAAgQAAAAAAAP///wECAwL/hI+py+EPo5y02otzZLz7DzbCSJbmiabqyrYuGYTyTHPBi+f6/sb1DwTdeMSikeULKpeH4fEJJSaZ1J8zis2uptVu6KoNi7nesk2MHpvXHXD6bSSz5264XSefr+v3fiuvV8bnR4gCGNg1WLg4cohIpchY6Pi4FCnpR1kZdIl5p7lp5TkqABpK00maZnoqk6qq1ur1CqvFKvtBW4t1i9u2u9jrKwJMKDysoFt8dIyMoLxc1OxsAB3NM01tfY1HrbTNjZPtDP6345Dpzfmm61Teow70voUH8xkvurqF3jgBN45snopB7uw1uocPFbsUYIYUtANwmECGFEs4NPgvoUJ9/4YkHPyYUaOrhYYqlkIoUgjJEw1BTtyS8stKlhgfhozp4SVLjzD4ufSJJqIvneFY4sxVlN3RnElXLf3VNNbTBUSjlppKzGoWobiqRuUqy2tTsK3EJiV7ymxRtKHUhmO7yS03uJXkXqP7yG40vIj0LuMbyG8xwHoEAyNMR6strFQVb2WczDGvwBoqW34gGV7hwJmh4P3c+clnzqHjBCZdWsrpwqmlrU7cGttrNoZ3jWYd+9zsPbl1b8bdW9xuM7Vr3aZzObny5cyHCwqe4zht6MJ/w6b+x/ks7C6k8+aORHsi8OGtTyc/UHyV4rC8E0ef3vx3+Eblv6dfnw5q/DDUQ//ib4J7zwHYn30DEniVgdshmKB+wBEo4IIIRjgegxSux2CDtO0H4IX/WegfE+yp4qGIGZZoyYkhpgiighVOuOI3tvAE0kDGxLjOVjSJY9JjLmKo447d9TjZjx/yUtJJFqFzEWb9AOUZjvLYkuQV7jhkU1UoyhikRTUFWKNNPjp4XRT+fOmlki5JteGDnqWJpkFWYjRmm2W+CaeaLampJ5t7cCgamHF+NGeNRZJ5HpKC8nllmHQeameiZlYZIJOOPrmYkSaSyMiWOQaT542astipk51KmQ+Mo3KpKqLzQYhqDSOS4umULbp6X6uRvtphrBvp+qeb/NWaKqyrfmosrgf/JrtrrswGe+ewvs4w6yjEyqrisbZSx1y3EgCKH10OgEufuKDduse5wAqi7rPskgufufCiJ6+w4RbWbq/IzUtevdHeuy++3g5McLf48guev5LqS1u+0gb8b7kH2ysxxAs/3DDC3CnMK8bpaowdx84y/DHF8U4c8ckWdwxwxibTi/LFLZeccndnjhUzyzwuaqOhweQ8cj1CmjSryMuekySmT0aw5JxOmuraykFHN3SWj2bZqM/dSH00HjTyqaSYexaqdXRAd031omPTuTbbzJwtITaUpim2oGSD7ZvLNZuzY9uM2p1nOUbHjXTfgF8qZ+Bvc0240IqvaajVbpvG+IvY/3ytNKZQb/541HrLXPHnOqss+tSh0ww66aiPDnPlQK47i8MzEyf76bSDzC3clpN8+8v96v66u7HjDt3gu3vc+94JA3+k8InUrnryqbdeOtq2v+v78q5DUnD33mvA/KawP098cMYHzzv2ym8cPqnOrwc99aubHr360/++/RdnoJvAuN9EBIH+ZasJD+Ae7cZVLU/EIICx+97NIOTADaRrgSoq4FH8V40BAgCD+LDgMzRYDQ4GBBAJxAQJl1JCSSDmftqDTBNWQQHbuPCDENnLDF9Yw7/cMIM53ElBoOaUHcqlDg/xiVtWyDpFheoGewriDYc4tJM0MSg73OAnoshEnmb5CTJQ1GIWQxUGJNKvS1cDm1rEaD0qCQlLj9oiY7roQ3sAkYpCtM0kqphCvN1khnkUDBobNzsuglCQ/CPk+KaSx5/VsZBvHGQjGYmVRN5xkYd8iiRF9URHRlKTiOSkJSMISlAGogAAOw==</binary>
<binary id="13" content-type="image/gif">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</binary>
<binary id="14" content-type="image/gif">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</binary>
<binary id="15" content-type="image/gif">R0lGODlh3gJ2AHcAMSH+GlNvZnR3YXJlOiBNaWNyb3NvZnQgT2ZmaWNlACH5BAEAAAAALBoAAgDEAnIAgQAAAODg4P///wECAwL/lI+py+0Po5y02ouz3rz7D4biSJbmiabqyrbuC8fyTNf2jef6zvf+DwwKh8Si8YhMKpfMpvMJjUqn1Kr1is1qt9yu9wsOi8fksvmMTqvX7Lb7DY/L5/S6/Y7P6/f8vv8PGCg4SFhoeIiYqLjI2Oj4CBkpOUlZaXmJmam5ydnp+QkaKjpKWmp6ipqqusra6voKGyA7S1tre4ubq7vL2+v7CxwsPExcbHyMnKy8zNzs/AwdLT1NDe1QjZ2tvc3d7f0NHi4+Tl6OfW2err7O3u7+Dh8vP3+LTn+Pn6+/z9/v/7/LHsCBBAsaPIgw4UCBChs6fAgxosSJuhhSvIgxo8aN/xy5WewIMqTIkSQ3fiyJMqXKlSzdnWwJM6bMmTSLvayJM6fOnShv8vwJNKhQgz6HGj2KNKm5okqbOn0KVRnTqFSrWr069arWrVyBZu0KNqzYlF/Hmj2LVmLZtGzbuu239q3cuXTVxa2LN6/eanf3+v0LmFjfwIQLG541+LDixXgTM34MGa3jyJQra51sObNmpZg3e/7MszPo0aRhii6NOrXI06pbu6bI+rXs2Qhj076Nm5/t3Lx7w9vtO7hwcsCHGz+urTjy5cydKW8OPbrgBtKrWw/3/Lr27QGyc/8e3Tv48cjFkz8f3Dz69bjVs3//2j38+ajl07//2T7+/Zb189///5h/AA5omIAEHviXgQgu2Bh1DD7om4IQTpiWhBReKJaFGG64lYYcfkiVhyCO2JSIJJ5olIkorviTiiy+iJOLMM4Yk4w03qiSjTjuOJKOPP7IkY9ADnmRkEQeCZGRSC6ZkJJMPkmQk1BOCZeDVF5ZopVYbpmillx+2aKXYI4Zo5hknlmjmWiumaOabL7Zo5twzhmknHTeWaSdeO6ZpJ58/tmkn4AOGqWghB5aJQOILhqooow+WqijkE6a6AKUXrqPlJheCkunnn4Kaqiijkpqqaaeimqqqq7KaquuplEAADs=</binary>
</FictionBook>