- •Thinking in C++ 2nd edition Volume 2: Standard Libraries & Advanced Topics
- •Preface
- •What’s new in the second edition
- •What’s in Volume 2 of this book
- •How to get Volume 2
- •Prerequisites
- •Learning C++
- •Goals
- •Chapters
- •Exercises
- •Exercise solutions
- •Source code
- •Language standards
- •Language support
- •The book’s CD ROM
- •Seminars, CD Roms & consulting
- •Errors
- •Acknowledgements
- •Library overview
- •1: Strings
- •What’s in a string
- •Creating and initializing C++ strings
- •Initialization limitations
- •Operating on strings
- •Appending, inserting and concatenating strings
- •Replacing string characters
- •Concatenation using non-member overloaded operators
- •Searching in strings
- •Finding in reverse
- •Finding first/last of a set
- •Removing characters from strings
- •Stripping HTML tags
- •Comparing strings
- •Using iterators
- •Iterating in reverse
- •Strings and character traits
- •A string application
- •Summary
- •Exercises
- •2: Iostreams
- •Why iostreams?
- •True wrapping
- •Iostreams to the rescue
- •Sneak preview of operator overloading
- •Inserters and extractors
- •Manipulators
- •Common usage
- •Line-oriented input
- •Overloaded versions of get( )
- •Reading raw bytes
- •Error handling
- •File iostreams
- •Open modes
- •Iostream buffering
- •Seeking in iostreams
- •Creating read/write files
- •User-allocated storage
- •Output strstreams
- •Automatic storage allocation
- •Proving movement
- •A better way
- •Output stream formatting
- •Internal formatting data
- •Format fields
- •Width, fill and precision
- •An exhaustive example
- •Formatting manipulators
- •Manipulators with arguments
- •Creating manipulators
- •Effectors
- •Iostream examples
- •Code generation
- •Maintaining class library source
- •Detecting compiler errors
- •A simple datalogger
- •Generating test data
- •Verifying & viewing the data
- •Counting editor
- •Breaking up big files
- •Summary
- •Exercises
- •3: Templates in depth
- •Nontype template arguments
- •Typedefing a typename
- •Using typename instead of class
- •Function templates
- •A string conversion system
- •A memory allocation system
- •Type induction in function templates
- •Taking the address of a generated function template
- •Local classes in templates
- •Applying a function to an STL sequence
- •Template-templates
- •Member function templates
- •Why virtual member template functions are disallowed
- •Nested template classes
- •Template specializations
- •A practical example
- •Pointer specialization
- •Partial ordering of function templates
- •Design & efficiency
- •Preventing template bloat
- •Explicit instantiation
- •Explicit specification of template functions
- •Controlling template instantiation
- •Template programming idioms
- •Summary
- •Containers and iterators
- •STL reference documentation
- •The Standard Template Library
- •The basic concepts
- •Containers of strings
- •Inheriting from STL containers
- •A plethora of iterators
- •Iterators in reversible containers
- •Iterator categories
- •Input: read-only, one pass
- •Output: write-only, one pass
- •Forward: multiple read/write
- •Bidirectional: operator--
- •Random-access: like a pointer
- •Is this really important?
- •Predefined iterators
- •IO stream iterators
- •Manipulating raw storage
- •Basic sequences: vector, list & deque
- •Basic sequence operations
- •vector
- •Cost of overflowing allocated storage
- •Inserting and erasing elements
- •deque
- •Converting between sequences
- •Cost of overflowing allocated storage
- •Checked random-access
- •list
- •Special list operations
- •list vs. set
- •Swapping all basic sequences
- •Robustness of lists
- •Performance comparison
- •A completely reusable tokenizer
- •stack
- •queue
- •Priority queues
- •Holding bits
- •bitset<n>
- •vector<bool>
- •Associative containers
- •Generators and fillers for associative containers
- •The magic of maps
- •A command-line argument tool
- •Multimaps and duplicate keys
- •Multisets
- •Combining STL containers
- •Creating your own containers
- •Summary
- •Exercises
- •5: STL Algorithms
- •Function objects
- •Classification of function objects
- •Automatic creation of function objects
- •Binders
- •Function pointer adapters
- •SGI extensions
- •A catalog of STL algorithms
- •Support tools for example creation
- •Filling & generating
- •Example
- •Counting
- •Example
- •Manipulating sequences
- •Example
- •Searching & replacing
- •Example
- •Comparing ranges
- •Example
- •Removing elements
- •Example
- •Sorting and operations on sorted ranges
- •Sorting
- •Example
- •Locating elements in sorted ranges
- •Example
- •Merging sorted ranges
- •Example
- •Set operations on sorted ranges
- •Example
- •Heap operations
- •Applying an operation to each element in a range
- •Examples
- •Numeric algorithms
- •Example
- •General utilities
- •Creating your own STL-style algorithms
- •Summary
- •Exercises
- •Perspective
- •Duplicate subobjects
- •Ambiguous upcasting
- •virtual base classes
- •The "most derived" class and virtual base initialization
- •"Tying off" virtual bases with a default constructor
- •Overhead
- •Upcasting
- •Persistence
- •MI-based persistence
- •Improved persistence
- •Avoiding MI
- •Mixin types
- •Repairing an interface
- •Summary
- •Exercises
- •7: Exception handling
- •Error handling in C
- •Throwing an exception
- •Catching an exception
- •The try block
- •Exception handlers
- •Termination vs. resumption
- •The exception specification
- •Better exception specifications?
- •Catching any exception
- •Rethrowing an exception
- •Uncaught exceptions
- •Function-level try blocks
- •Cleaning up
- •Constructors
- •Making everything an object
- •Exception matching
- •Standard exceptions
- •Programming with exceptions
- •When to avoid exceptions
- •Not for asynchronous events
- •Not for ordinary error conditions
- •Not for flow-of-control
- •You’re not forced to use exceptions
- •New exceptions, old code
- •Typical uses of exceptions
- •Always use exception specifications
- •Start with standard exceptions
- •Nest your own exceptions
- •Use exception hierarchies
- •Multiple inheritance
- •Catch by reference, not by value
- •Throw exceptions in constructors
- •Don’t cause exceptions in destructors
- •Avoid naked pointers
- •Overhead
- •Summary
- •Exercises
- •8: Run-time type identification
- •The “Shape” example
- •What is RTTI?
- •Two syntaxes for RTTI
- •Syntax specifics
- •Producing the proper type name
- •Nonpolymorphic types
- •Casting to intermediate levels
- •void pointers
- •Using RTTI with templates
- •References
- •Exceptions
- •Multiple inheritance
- •Sensible uses for RTTI
- •Revisiting the trash recycler
- •Mechanism & overhead of RTTI
- •Creating your own RTTI
- •Explicit cast syntax
- •Summary
- •Exercises
- •9: Building stable systems
- •Shared objects & reference counting
- •Reference-counted class hierarchies
- •Finding memory leaks
- •An extended canonical form
- •Exercises
- •10: Design patterns
- •The pattern concept
- •The singleton
- •Variations on singleton
- •Classifying patterns
- •Features, idioms, patterns
- •Basic complexity hiding
- •Factories: encapsulating object creation
- •Polymorphic factories
- •Abstract factories
- •Virtual constructors
- •Destructor operation
- •Callbacks
- •Observer
- •The “interface” idiom
- •The “inner class” idiom
- •The observer example
- •Multiple dispatching
- •Visitor, a type of multiple dispatching
- •Efficiency
- •Flyweight
- •The composite
- •Evolving a design: the trash recycler
- •Improving the design
- •“Make more objects”
- •A pattern for prototyping creation
- •Trash subclasses
- •Parsing Trash from an external file
- •Recycling with prototyping
- •Abstracting usage
- •Applying double dispatching
- •Implementing the double dispatch
- •Applying the visitor pattern
- •More coupling?
- •RTTI considered harmful?
- •Summary
- •Exercises
- •11: Tools & topics
- •The code extractor
- •Debugging
- •Trace macros
- •Trace file
- •Abstract base class for debugging
- •Tracking new/delete & malloc/free
- •CGI programming in C++
- •Encoding data for CGI
- •The CGI parser
- •Testing the CGI parser
- •Using POST
- •Handling mailing lists
- •Maintaining your list
- •Mailing to your list
- •A general information-extraction CGI program
- •Parsing the data files
- •Summary
- •Exercises
- •General C++
- •My own list of books
- •Depth & dark corners
- •Design Patterns
- •Index
as function objects). The classification of function objects in the STL is based on whether the operator( ) takes zero, one or two arguments, and if it returns a bool or non-bool value.
Generator: Takes no arguments, and returns a value of the desired type. A
RandomNumberGenerator is a special case.
UnaryFunction: Takes a single argument of any type and returns a value which may be of a different type.
BinaryFunction: Takes two arguments of any two types and returns a value of any type.
A special case of the unary and binary functions is the predicate, which simply means a function that returns a bool. A predicate is a function you use to make a true/false decision.
Predicate: This can also be called a UnaryPredicate. It takes a single argument of any type and returns a bool.
BinaryPredicate: Takes two arguments of any two types and returns a bool.
StrictWeakOrdering: A binary predicate that says that if you have two objects and neither one is less than the other, they can be regarded as equivalent to each other.
In addition, there are sometimes qualifications on object types that are passed to an algorithm. These qualifications are given in the template argument type identifier name:
LessThanComparable: A class that has a less-than operator<.
Assignable: A class that has an assignment operator= for its own type. EqualityComparable: A class that has an equivalence operator== for its own type.
Automatic creation of function objects
The STL has, in the header file <functional>, a set of templates that will automatically create function objects for you. These generated function objects are admittedly simple, but the goal is to provide very basic functionality that will allow you to compose more complicated function objects, and in many situations this is all you’ll need. Also, you’ll see that there are some function object adapters that allow you to take the simple function objects and make them slightly more complicated.
Here are the templates that generate function objects, along with the expressions that they effect.
Name |
Type |
Result produced by generated function |
|
|
object |
|
|
|
plus |
BinaryFunction |
arg1 + arg2 |
|
|
|
minus |
BinaryFunction |
arg1 - arg2 |
|
|
|
multiplies |
BinaryFunction |
arg1 * arg2 |
|
|
|
Chapter 15: Multiple Inheritance
265
Name |
Type |
Result produced by generated function |
|
|
object |
|
|
|
divides |
BinaryFunction |
arg1 / arg2 |
|
|
|
modulus |
BinaryFunction |
arg1 % arg2 |
|
|
|
negate |
UnaryFunction |
- arg1 |
|
|
|
equal_to |
BinaryPredicate |
arg1 == arg2 |
|
|
|
not_equal_to |
BinaryPredicate |
arg1 != arg2 |
|
|
|
greater |
BinaryPredicate |
arg1 > arg2 |
|
|
|
less |
BinaryPredicate |
arg1 < arg2 |
|
|
|
greater_equal |
BinaryPredicate |
arg1 >= arg2 |
|
|
|
less_equal |
BinaryPredicate |
arg1 <= arg2 |
|
|
|
logical_and |
BinaryPredicate |
arg1 && arg2 |
|
|
|
logical_or |
BinaryPredicate |
arg1 || arg2 |
|
|
|
logical_not |
UnaryPredicate |
!arg1 |
|
|
|
not1( ) |
Unary Logical |
!(UnaryPredicate(arg1)) |
|
|
|
not2( ) |
Binary Logical |
!(BinaryPredicate(arg1, arg2)) |
|
|
|
The following example provides simple tests for each of the built-in basic function object templates. This way, you can see how to use each one, along with their resulting behavior.
//: C05:FunctionObjects.cpp
//Using the predefined function object templates
//in the Standard C++ library
//This will be defined shortly:
#include "Generators.h" #include <algorithm> #include <vector> #include <iostream> #include <functional> using namespace std;
template<typename T>
void print(vector<T>& v, char* msg = "") { if(*msg != 0)
cout << msg << ":" << endl;
Chapter 15: Multiple Inheritance
266
copy(v.begin(), v.end(), ostream_iterator<T>(cout, " "));
cout << endl;
}
template<typename Contain, typename UnaryFunc> void testUnary(Contain& source, Contain& dest,
UnaryFunc f) { transform(source.begin(), source.end(),
dest.begin(), f);
}
template<typename Contain1, typename Contain2, typename BinaryFunc>
void testBinary(Contain1& src1, Contain1& src2, Contain2& dest, BinaryFunc f) { transform(src1.begin(), src1.end(),
src2.begin(), dest.begin(), f);
}
//Executes the expression, then stringizes the
//expression into the print statement:
#define T(EXPR) EXPR; print(r, "After " #EXPR); // For Boolean tests:
#define B(EXPR) EXPR; print(br,"After " #EXPR);
// Boolean random generator: struct BRand {
BRand() { srand(time(0)); } bool operator()() {
return rand() > RAND_MAX / 2;
}
};
int main() {
const int sz = 10; const int max = 50;
vector<int> x(sz), y(sz), r(sz);
//An integer random number generator: URandGen urg(max); generate_n(x.begin(), sz, urg); generate_n(y.begin(), sz, urg);
//Add one to each to guarantee nonzero divide:
Chapter 15: Multiple Inheritance
267
transform(y.begin(), y.end(), y.begin(), bind2nd(plus<int>(), 1));
//Guarantee one pair of elements is ==: x[0] = y[0];
print(x, "x"); print(y, "y");
//Operate on each element pair of x & y,
//putting the result into r: T(testBinary(x, y, r, plus<int>())); T(testBinary(x, y, r, minus<int>())); T(testBinary(x, y, r, multiplies<int>())); T(testBinary(x, y, r, divides<int>())); T(testBinary(x, y, r, modulus<int>())); T(testUnary(x, r, negate<int>())); vector<bool> br(sz); // For Boolean results B(testBinary(x, y, br, equal_to<int>()));
B(testBinary(x, y, br, not_equal_to<int>())); B(testBinary(x, y, br, greater<int>())); B(testBinary(x, y, br, less<int>())); B(testBinary(x, y, br, greater_equal<int>())); B(testBinary(x, y, br, less_equal<int>())); B(testBinary(x, y, br,
not2(greater_equal<int>()))); B(testBinary(x,y,br,not2(less_equal<int>()))); vector<bool> b1(sz), b2(sz); generate_n(b1.begin(), sz, BRand()); generate_n(b2.begin(), sz, BRand());
print(b1, "b1"); print(b2, "b2");
B(testBinary(b1, b2, br, logical_and<int>())); B(testBinary(b1, b2, br, logical_or<int>())); B(testUnary(b1, br, logical_not<int>())); B(testUnary(b1, br, not1(logical_not<int>())));
}///:~
To keep this example small, some tools are created. The print( ) template is designed to print any vector<T>, along with an optional message. Since print( ) uses the STL copy( ) algorithm to send objects to cout via an ostream_iterator, the ostream_iterator must know the type of object it is printing, and therefore the print( ) template must know this type also. However, you’ll see in main( ) that the compiler can deduce the type of T when you hand it a vector<T>, so you don’t have to hand it the template argument explicitly; you just say print(x) to print the vector<T> x.
Chapter 15: Multiple Inheritance
268