6.8. DetailsAbstractionAn idea that emphasizes high-level concepts and de-emphasizes implementation details. Classes in runtime C++ are one kind of abstraction commonly used to package state with associated processes. Functions are one of the most fundamental kinds of abstraction and are obviously important in any functional programming context. The MPL algorithms are abstractions of repetitive processes and are implemented as metafunctions. The abstraction value of algorithms in MPL is often higher than that of corresponding STL algorithms simply because the alternative to using them is so much worse at compile time. While we can traverse an STL sequence with a for loop and a couple of iterators, a hand-rolled compile-time sequence traversal always requires at least one new class template and an explicit specialization. FoldA primitive functional abstraction that applies a binary function repeatedly to the elements of a sequence and an additional value, using the result of the function at each step as the additional value for the next step. The STL captures the same abstraction under the name accumulate. MPL generalizes fold in two ways: by operating on iterators instead of elements (iter_fold) and by supplying bidirectional traversal (reverse_[iter_] fold). Querying algorithmsMPL supports a variety of algorithms that return iterators or simple values; these generally correspond exactly to STL algorithms of the same names. Sequence building algorithmsThe STL algorithms that require Output Iterators arguments correspond to pairs of forward and backward MPL "sequence building" algorithms that, by default, construct new sequences of the same kind as their first input sequence. They also accept an optional inserter argument that gives greater control over the algorithm's result. InsertersIn the STL tradition, a function whose name ends with inserter creates an output iterator for adding elements to a sequence. MPL uses the term to denote a binary metafunction packaged with an additional value, which is used as an output processor for the result elements of an algorithm. The default inserters used by the algorithms are front_inserter<S> and back_inserter<S>; they fold the results into S using push_front or push_back. Using an inserter with an algorithm is equivalent to applying fold to the algorithm's default (no-inserter) result, the inserter's function, and its initial state. It follows that there's no reason an inserter (or a sequence building algorithm) needs to build new sequences; it can produce an arbitrary result depending on its function component. |