generic_programming.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
  2. <html>
  3. <head>
  4. <meta name="generator" content="HTML Tidy, see www.w3.org">
  5. <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
  6. <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
  7. <meta name="ProgId" content="FrontPage.Editor.Document">
  8. <title>Generic Programming Techniques</title>
  9. </head>
  10. <body bgcolor="#FFFFFF" text="#000000">
  11. <img src="../c++boost.gif" alt="c++boost.gif (8819 bytes)" align="center"
  12. width="277" height="86">
  13. <h1>Generic Programming Techniques</h1>
  14. <p>This is an incomplete survey of some of the generic programming
  15. techniques used in the <a href="../index.htm">boost</a> libraries.
  16. <h2>Table of Contents</h2>
  17. <ul>
  18. <li><a href="#traits">Traits</a>
  19. <li><a href="#tag_dispatching">Tag Dispatching</a>
  20. <li><a href="#type_generator">Type Generators</a>
  21. <li><a href="#object_generator">Object Generators</a>
  22. <li><a href="#policies">Policies Classes</a>
  23. <li><a href="#adaptors">Adaptors</a>
  24. </ul>
  25. <h2><a name="traits">Traits</a></h2>
  26. <p>A traits class provides a way of associating information with a
  27. compile-time entity (a type, integral constant, or address). For example,
  28. the class template <tt><a href=
  29. "http://www.sgi.com/tech/stl/iterator_traits.html">std::iterator_traits&lt;T&gt;</a></tt>
  30. looks something like this:
  31. <blockquote>
  32. <pre>
  33. template &lt;class Iterator&gt;
  34. struct iterator_traits {
  35. typedef ... iterator_category;
  36. typedef ... value_type;
  37. typedef ... difference_type;
  38. typedef ... pointer;
  39. typedef ... reference;
  40. };
  41. </pre>
  42. </blockquote>
  43. The traits' <tt>value_type</tt> gives generic code the type which the
  44. iterator is "pointing at", while the <tt>iterator_category</tt> can be used
  45. to select more efficient algorithms depending on the iterator's
  46. capabilities.
  47. <p>A key feature of traits templates is that they're <i>non-intrusive</i>:
  48. they allow us to associate information with arbitrary types, including
  49. built-in types and types defined in third-party libraries, Normally, traits
  50. are specified for a particular type by (partially) specializing the traits
  51. template.
  52. <p>For an in-depth description of <tt>std::iterator_traits</tt>, see <a href=
  53. "http://www.sgi.com/tech/stl/iterator_traits.html">this page</a> provided
  54. by SGI. Another very different expression of the traits idiom in the
  55. standard is <tt>std::numeric_limits&lt;T&gt;</tt> which provides constants
  56. describing the range and capabilities of numeric types.
  57. <h2><a name="tag_dispatching">Tag Dispatching</a></h2>
  58. <p>
  59. A technique that often goes hand in hand with traits classes is
  60. tag dispatching, which is a way of using function overloading to
  61. dispatch based on properties of a type. A good example of this is
  62. the implementation of the <a
  63. href="http://www.sgi.com/tech/stl/advance.html"><tt>std::advance()</tt></a>
  64. function in the C++ Standard Library, which increments an
  65. iterator <tt>n</tt> times. Depending on the kind of iterator,
  66. there are different optimizations that can be applied in the
  67. implementation. If the iterator is <a
  68. href="http://www.sgi.com/tech/stl/RandomAccessIterator.html">random
  69. access</a> (can jump forward and backward arbitrary distances),
  70. then the <tt>advance()</tt> function can simply be implemented
  71. with <tt>i += n</tt>, and is very efficient: constant time. If
  72. the iterator is <a
  73. href="http://www.sgi.com/tech/stl/BidirectionalIterator.html">bidirectional</a>,
  74. then it makes sense for <tt>n</tt> to be negative, we can
  75. decrement the iterator <tt>n</tt> times.
  76. </p>
  77. <p>
  78. The relation between tag dispatching and traits classes is
  79. that the property used for dispatching (in this case the
  80. <tt>iterator_category</tt>) is accessed through a traits class.
  81. The main <tt>advance()</tt> function uses the <a
  82. href="http://www.sgi.com/tech/stl/iterator_traits.html"><tt>iterator_traits</tt></a>
  83. class to get the <tt>iterator_category</tt>. It then makes a call
  84. the the overloaded <tt>advance_dispatch()</tt> function.
  85. The
  86. appropriate <tt>advance_dispatch()</tt> is selected by the
  87. compiler based on whatever type the <tt>iterator_category</tt>
  88. resolves to, either <a
  89. href="http://www.sgi.com/tech/stl/input_iterator_tag.html">
  90. <tt>input_iterator_tag</tt></a>, <a
  91. href="http://www.sgi.com/tech/stl/bidirectional_iterator_tag.html">
  92. <tt>bidirectional_iterator_tag</tt></a>, or <a
  93. href="http://www.sgi.com/tech/stl/random_access_iterator_tag.html">
  94. <tt>random_access_iterator_tag</tt></a>. A <b><i>tag</i></b> is
  95. simply a class whose only purpose is to convey some property for
  96. use in tag dispatching and similar techniques. Refer to <a
  97. href="http://www.sgi.com/tech/stl/iterator_tags.html">this
  98. page</a> for a more detailed description of iterator tags.
  99. </p>
  100. <blockquote>
  101. <pre>
  102. namespace std {
  103. struct input_iterator_tag { };
  104. struct bidirectional_iterator_tag { };
  105. struct random_access_iterator_tag { };
  106. namespace detail {
  107. template &lt;class InputIterator, class Distance&gt;
  108. void advance_dispatch(InputIterator&amp; i, Distance n, <b>input_iterator_tag</b>) {
  109. while (n--) ++i;
  110. }
  111. template &lt;class BidirectionalIterator, class Distance&gt;
  112. void advance_dispatch(BidirectionalIterator&amp; i, Distance n,
  113. <b>bidirectional_iterator_tag</b>) {
  114. if (n &gt;= 0)
  115. while (n--) ++i;
  116. else
  117. while (n++) --i;
  118. }
  119. template &lt;class RandomAccessIterator, class Distance&gt;
  120. void advance_dispatch(RandomAccessIterator&amp; i, Distance n,
  121. <b>random_access_iterator_tag</b>) {
  122. i += n;
  123. }
  124. }
  125. template &lt;class InputIterator, class Distance&gt;
  126. void advance(InputIterator&amp; i, Distance n) {
  127. typename <b>iterator_traits&lt;InputIterator&gt;::iterator_category</b> category;
  128. detail::advance_dispatch(i, n, <b>category</b>);
  129. }
  130. }
  131. </pre>
  132. </blockquote>
  133. <h2><a name="type_generator">Type Generators</a></h2>
  134. <p>A <i>type generator</i> is a template whose only purpose is to
  135. synthesize a single new type based on its template argument(s). The
  136. generated type is usually expressed as a nested typedef named,
  137. appropriately <tt>type</tt>. A type generator is usually used to
  138. consolidate a complicated type expression into a simple one, as in
  139. <tt>boost::<a href=
  140. "../libs/utility/filter_iterator.hpp">filter_iterator_generator</a></tt>,
  141. which looks something like this:
  142. <blockquote>
  143. <pre>
  144. template &lt;class Predicate, class Iterator,
  145. class Value = <i>complicated default</i>,
  146. class Reference = <i>complicated default</i>,
  147. class Pointer = <i>complicated default</i>,
  148. class Category = <i>complicated default</i>,
  149. class Distance = <i>complicated default</i>
  150. &gt;
  151. struct filter_iterator_generator {
  152. typedef iterator_adaptor&lt;
  153. Iterator,filter_iterator_policies&lt;Predicate,Iterator&gt;,
  154. Value,Reference,Pointer,Category,Distance&gt; <b>type</b>;
  155. };
  156. </pre>
  157. </blockquote>
  158. <p>Now, that's complicated, but producing an adapted filter iterator is
  159. much easier. You can usually just write:
  160. <blockquote>
  161. <pre>
  162. boost::filter_iterator_generator&lt;my_predicate,my_base_iterator&gt;::type
  163. </pre>
  164. </blockquote>
  165. <h2><a name="object_generator">Object Generators</a></h2>
  166. <p>An <i>object generator</i> is a function template whose only purpose is
  167. to construct a new object out of its arguments. Think of it as a kind of
  168. generic constructor. An object generator may be more useful than a plain
  169. constructor when the exact type to be generated is difficult or impossible
  170. to express and the result of the generator can be passed directly to a
  171. function rather than stored in a variable. Most object generators are named
  172. with the prefix "<tt>make_</tt>", after <tt>std::<a href=
  173. "http://www.sgi.com/tech/stl/pair.html">make_pair</a>(const T&amp;, const U&amp;)</tt>.
  174. <p>Here is an example, using another standard object generator, <tt>std::<a
  175. href=
  176. "http://www.sgi.com/tech/stl/back_insert_iterator.html">back_inserter</a>()</tt>:
  177. <blockquote>
  178. <pre>
  179. // Append the items in [start, finish) to c
  180. template &lt;class Container, class Iterator&gt;
  181. void append_sequence(Container&amp; c, Iterator start, Iterator finish)
  182. {
  183. std::copy(start, finish, <b>std::back_inserter</b>(c));
  184. }
  185. </pre>
  186. </blockquote>
  187. <p>Without using the object generator the example above would look like:
  188. write:
  189. <blockquote>
  190. <pre>
  191. // Append the items in [start, finish) to c
  192. template &lt;class Container, class Iterator&gt;
  193. void append_sequence(Container&amp; c, Iterator start, Iterator finish)
  194. {
  195. std::copy(start, finish, <b>std::back_insert_iterator&lt;Container&gt;</b>(c));
  196. }
  197. </pre>
  198. </blockquote>
  199. <p>As expressions get more complicated the need to reduce the verbosity of
  200. type specification gets more compelling.
  201. <h2><a name="policies">Policies Classes</a></h2>
  202. <p>A policies class is a template parameter used to transmit
  203. behaviors. An example from the standard library is <tt>std::<a
  204. href="http://www.dinkumware.com/htm_cpl/memory.html#allocator"></a></tt>,
  205. which supplies memory management behaviors to standard <a
  206. href="http://www.sgi.com/tech/stl/Container.html">containers</a>.
  207. <p>Policies classes have been explored in detail by <a href=
  208. "mailto:andrewalex@hotmail.com">Andrei Alexandrescu</a> in <a href=
  209. "http://www.cs.ualberta.ca/~hoover/cmput401/XP-Notes/xp-conf/Papers/7_3_Alexandrescu.pdf">
  210. this paper</a>. He writes:
  211. <blockquote>
  212. <p>Policy classes are implementations of punctual design choices. They
  213. are inherited from, or contained within, other classes. They provide
  214. different strategies under the same syntactic interface. A class using
  215. policies is templated having one template parameter for each policy it
  216. uses. This allows the user to select the policies needed.
  217. <p>The power of policy classes comes from their ability to combine
  218. freely. By combining several policy classes in a template class with
  219. multiple parameters, one achieves combinatorial behaviors with a linear
  220. amount of code.
  221. </blockquote>
  222. <p>Andrei's description of policies describe their power as being derived
  223. from their granularity and orthogonality. Boost has probably diluted the
  224. distinction in the <a href="../libs/utility/iterator_adaptors.htm">Iterator
  225. Adaptors</a> library, where we transmit all of an adapted iterator's
  226. behavior in a single policies class. There is precedent for this, however:
  227. <tt><a
  228. href="http://www.dinkumware.com/htm_cpl/string2.html#char_traits">std::char_traits</a></tt>,
  229. despite its name, acts as a policies class that determines the behaviors of
  230. <a
  231. href="http://www.dinkumware.com/htm_cpl/string2.html#basic_string">std::basic_string</a>.
  232. <h2><a name="adaptors">Adaptors</a></h2>
  233. <p>An <i>adaptor</i> is a class template which builds on another type or
  234. types to provide a new interface or behavioral variant. Examples of
  235. standard adaptors are <a href=
  236. "http://www.sgi.com/tech/stl/ReverseIterator.html">std::reverse_iterator</a>,
  237. which adapts an iterator type by reversing its motion upon
  238. increment/decrement, and <a href=
  239. "http://www.sgi.com/tech/stl/stack.html">std::stack</a>, which adapts a
  240. container to provide a simple stack interface.
  241. <p>A more comprehensive review of the adaptors in the standard can be found
  242. <a href=
  243. "http://www.cs.rpi.edu/~wiseb/xrds/ovp2-3b.html#SECTION00015000000000000000">
  244. here</a>.
  245. <hr>
  246. <p>Revised
  247. <!--webbot bot="Timestamp" s-type="EDITED" s-format="%d %b %Y" startspan -->12 Feb 2001<!--webbot bot="Timestamp" endspan i-checksum="14377" -->
  248. <p>&copy; Copyright David Abrahams 2001. Permission to copy, use, modify,
  249. sell and distribute this document is granted provided this copyright notice
  250. appears in all copies. This document is provided "as is" without express or
  251. implied warranty, and with no claim as to its suitability for any purpose.
  252. <!-- LocalWords: HTML html charset gif alt htm struct SGI namespace std libs
  253. -->
  254. <!-- LocalWords: InputIterator BidirectionalIterator RandomAccessIterator pdf
  255. -->
  256. <!-- LocalWords: typename Alexandrescu templated Andrei's Abrahams
  257. -->
  258. </body>
  259. </html>
粤ICP备19079148号