diff --git a/generic_programming.html b/generic_programming.html index 46ebe8c..8f9dcf5 100644 --- a/generic_programming.html +++ b/generic_programming.html @@ -1,16 +1,12 @@ - -
Generic programming is about generalizing software components - so that they can be easily reused in a wide variety of situations. - In C++, class and function templates are particularly effective - mechanisms for generic programming because they make the - generalization possible without sacrificing efficiency. - -
As a simple example of generic programming, we will look at how - one might generalize the memcpy() function of the - C standard library. An implementation of memcpy() - might look like the following: -
-
++ The memcpy() function is already generalized to some extent by the + use of void* so that the function can be used to copy arrays of + different kinds of data. But what if the data we would like to copy is not + in an array? Perhaps it is in a linked list. Can we generalize the notion + of copy to any sequence of elements? Looking at the body of + memcpy(), the function's minimal requirements are + that it needs to to traverse through the sequence using some sort of + pointer, access elements pointed to, write the elements to + the destination, and compare pointers to know when to stop. The C++ + standard library groups requirements such as these into + concepts, in this case the Input Iterator concept + (for region2) and the Output Iterator + concept (for region1). -Generic programming is about generalizing software components so that + they can be easily reused in a wide variety of situations. In C++, class + and function templates are particularly effective mechanisms for generic + programming because they make the generalization possible without + sacrificing efficiency. + +
As a simple example of generic programming, we will look at how one + might generalize the memcpy() function of the C standard library. + An implementation of memcpy() might look like the following: +
+
+ +- The memcpy() function is already generalized to some - extent by the use of void* so that the function can be - used to copy arrays of different kinds of data. But what if the - data we would like to copy is not in an array? Perhaps it is in a - linked list. Can we generalize the notion of copy to any sequence - of elements? Looking at the body of memcpy(), the - function's minimal requirements are that it needs to - to traverse through the sequence using some sort of - pointer, access elements pointed to, write the - elements to the destination, and compare pointers to know - when to stop. The C++ standard library groups requirements such - as these into concepts, in this case the Input - Iterator concept (for region2) and the Output - Iterator concept (for region1). +void* memcpy(void* region1, const void* region2, size_t n) { @@ -66,33 +61,33 @@ void* memcpy(void* region1, const void* region2, size_t n) return result; }-
If we rewrite the memcpy() as a function template, and
- use the
- Input Iterator and Output
+ If we rewrite the memcpy() as a function template, and use the
+ Input Iterator
+ and Output
Iterator concepts to describe the requirements on the template
- parameters, we can implement a highly reusable copy()
- function in the following way:
-
- Using the generic copy() function, we can now copy
- elements from any kind of sequence, including a linked list that
- exports iterators such as std::list.
-
- Using the generic copy() function, we can now copy elements
+ from any kind of sequence, including a linked list that exports iterators
+ such as std::list.
+ The concepts used in the C++ Standard Library are documented at
- the
- SGI STL site.
+ The concepts used in the C++ Standard Library are documented at the SGI STL site.
For an in-depth description of std::iterator_traits, see this page provided
- by SGI. Another very different expression of the traits idiom in the
- standard is std::numeric_limits<T> which provides constants
- describing the range and capabilities of numeric types.
+ For an in-depth description of std::iterator_traits, see this page
+ provided by SGI. Another very different expression of the traits idiom in
+ the standard is std::numeric_limits<T> which provides
+ constants describing the range and capabilities of numeric types.
- A technique that often goes hand in hand with traits classes is
- tag dispatching, which is a way of using function overloading to
- dispatch based on properties of a type. A good example of this is
- the implementation of the std::advance()
- function in the C++ Standard Library, which increments an
- iterator n times. Depending on the kind of iterator,
- there are different optimizations that can be applied in the
- implementation. If the iterator is random
- access (can jump forward and backward arbitrary distances),
- then the advance() function can simply be implemented
- with i += n, and is very efficient: constant time. If
- the iterator is bidirectional,
- then it makes sense for n to be negative, we can
- decrement the iterator n times.
-
- The relation between tag dispatching and traits classes is
- that the property used for dispatching (in this case the
- iterator_category) is accessed through a traits class.
- The main advance() function uses the iterator_traits
- class to get the iterator_category. It then makes a call
- the the overloaded advance_dispatch() function.
- The
- appropriate advance_dispatch() is selected by the
- compiler based on whatever type the iterator_category
- resolves to, either
- input_iterator_tag,
- bidirectional_iterator_tag, or
- random_access_iterator_tag. A tag is
- simply a class whose only purpose is to convey some property for
- use in tag dispatching and similar techniques. Refer to this
- page for a more detailed description of iterator tags.
- A technique that often goes hand in hand with traits classes is tag
+ dispatching, which is a way of using function overloading to dispatch based
+ on properties of a type. A good example of this is the implementation of
+ the std::advance()
+ function in the C++ Standard Library, which increments an iterator
+ n times. Depending on the kind of iterator, there are different
+ optimizations that can be applied in the implementation. If the iterator is
+ random
+ access (can jump forward and backward arbitrary distances), then the
+ advance() function can simply be implemented with i += n,
+ and is very efficient: constant time. If the iterator is bidirectional,
+ then it makes sense for n to be negative, we can decrement the
+ iterator n times.
+
+ The relation between tag dispatching and traits classes is that the
+ property used for dispatching (in this case the iterator_category)
+ is accessed through a traits class. The main advance() function
+ uses the iterator_traits
+ class to get the iterator_category. It then makes a call the the
+ overloaded advance_dispatch() function. The appropriate
+ advance_dispatch() is selected by the compiler based on whatever
+ type the iterator_category resolves to, either input_iterator_tag,
+ bidirectional_iterator_tag,
+ or random_access_iterator_tag.
+ A tag is simply a class whose only purpose is to convey some
+ property for use in tag dispatching and similar techniques. Refer to this page for a
+ more detailed description of iterator tags.
+
A type generator is a template whose only purpose is to
- synthesize a single new type based on its template argument(s)[1]. The generated type is usually expressed as a
- nested typedef named, appropriately type. A type
- generator is usually used to consolidate a complicated type
- expression into a simple one, as in boost::[1]. The generated type is usually expressed as a nested typedef
+ named, appropriately type. A type generator is usually used to
+ consolidate a complicated type expression into a simple one, as in
+ boost::filter_iterator_generator,
which looks something like this:
@@ -345,7 +328,6 @@ boost::filter_iterator_generator<my_predicate,my_base_iterator>::type
An object generator is a function template whose only purpose is
@@ -353,35 +335,45 @@ boost::filter_iterator_generator<my_predicate,my_base_iterator>::type
generic constructor. An object generator may be more useful than a plain
constructor when the exact type to be generated is difficult or impossible
to express and the result of the generator can be passed directly to a
- function rather than stored in a variable. Most object generators are named
- with the prefix "make_", after std::make_", after std::make_pair(const T&, const U&).
- Here is an example, using another standard object generator, std::back_inserter():
+ For example, given:
Without using the object generator the example above would look like:
- write:
+ Without using object generators the example above would look like this:
As expressions get more complicated the need to reduce the verbosity of
type specification gets more compelling.
- A policies class is a template parameter used to transmit
- behaviors. An example from the standard library is std::allocator,
- which supplies memory management behaviors to standard containers.
+ A policy class is a template parameter used to transmit behavior. An
+ example from the standard library is std::allocator,
+ which supplies memory management behaviors to standard containers.
- Policies classes have been explored in detail by Policy classes have been explored in detail by Andrei Alexandrescu in
this paper. He writes:
@@ -415,40 +407,38 @@ void append_sequence(Container& c, Iterator start, Iterator finish)
amount of code.
- Andrei's description of policies describe their power as being derived
- from their granularity and orthogonality. Boost has probably diluted the
- distinction in the Iterator
- Adaptors library, where we transmit all of an adapted iterator's
- behavior in a single policies class. There is precedent for this, however:
- std::char_traits,
+ Andrei's description of policy classes describe their power as being
+ derived from their granularity and orthogonality. Boost has probably
+ diluted the distinction in the Iterator Adaptors library,
+ where we transmit all of an adapted iterator's behavior in a single policy
+ class. There is precedent for this, however: std::char_traits,
despite its name, acts as a policies class that determines the behaviors of
- std::basic_string.
+ std::basic_string.
+ parameters, we can implement a highly reusable copy() function in
+ the following way:
+
-
+
+
+
+
template <typename InputIterator, typename OutputIterator>
OutputIterator
@@ -103,14 +98,16 @@ copy(InputIterator first, InputIterator last, OutputIterator result)
return result;
}
-
+
+
+
+
-
+
#include <list>
#include <vector>
@@ -133,45 +130,38 @@ int main()
std::cout << std::endl;
}
-Anatomy of a Concept
-
- A concept is a set requirements, where the
- requirements consist of valid expressions, associated types,
- invariants, and complexity guarantees. A type that satisfies the
- set of requirements is said to model the concept. A
- concept can extend the requirements of another concept, which is
- called refinement.
+ A concept is a set requirements, where the requirements
+ consist of valid expressions, associated types, invariants, and complexity
+ guarantees. A type that satisfies the set of requirements is said to
+ model the concept. A concept can extend the requirements of
+ another concept, which is called refinement.
-
- Traits
@@ -204,56 +194,49 @@ struct iterator_traits {
are specified for a particular type by (partially) specializing the traits
template.
- Tag Dispatching
-
-
namespace std {
@@ -269,16 +252,16 @@ namespace std {
template <class BidirectionalIterator, class Distance>
void advance_dispatch(BidirectionalIterator& i, Distance n,
- bidirectional_iterator_tag) {
+ bidirectional_iterator_tag) {
if (n >= 0)
- while (n--) ++i;
+ while (n--) ++i;
else
- while (n++) --i;
+ while (n++) --i;
}
template <class RandomAccessIterator, class Distance>
void advance_dispatch(RandomAccessIterator& i, Distance n,
- random_access_iterator_tag) {
+ random_access_iterator_tag) {
i += n;
}
}
@@ -311,11 +294,11 @@ namespace std {
Type Generators
Object Generators
+ By chaining two standard object generators, std::bind2nd()
+ and std::mem_fun(),
+ we can easily tweak all widgets:
+
+
-// Append the items in [start, finish) to c
-template <class Container, class Iterator>
-void append_sequence(Container& c, Iterator start, Iterator finish)
+struct widget {
+ void tweak(int);
+};
+std::vector<widget *> widget_ptrs;
+
+
+
-
+void tweak_all_widgets1(int arg)
{
- std::copy(start, finish, std::back_inserter(c));
+ for_each(widget_ptrs.begin(), widget_ptrs.end(),
+ bind2nd(std::mem_fun(&widget::tweak), arg));
}
@@ -389,15 +381,15 @@ void append_sequence(Container& c, Iterator start, Iterator finish)
-// Append the items in [start, finish) to c
-template <class Container, class Iterator>
-void append_sequence(Container& c, Iterator start, Iterator finish)
+void tweak_all_widgets2(int arg)
{
- std::copy(start, finish, std::back_insert_iterator<Container>(c));
+ for_each(struct_ptrs.begin(), struct_ptrs.end(),
+ std::binder2nd<std::mem_fun1_t<void, widget, int> >(
+ std::mem_fun1_t<void, widget, int>(&widget::tweak), arg));
}
Policies Classes
+ Policy Classes
- Notes
-
- [1] Type generators are a workaround for the lack
- of ``templated typedefs'' in C++.
-
+ [1] Type generators are a workaround for the lack of
+ ``templated typedefs'' in C++.
Revised - 12 Feb 2001 + 15 + Feb 2001
© Copyright David Abrahams 2001. Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or - implied warranty, and with no claim as to its suitability for any purpose. + implied warranty, and with no claim as to its suitability for any purpose. + + + + + - - - - - -