generic_programming.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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="#introduction">Introduction</a>
  19. <li><a href="#concept">The Anatomy of a Concept</a>
  20. <li><a href="#traits">Traits</a>
  21. <li><a href="#tag_dispatching">Tag Dispatching</a>
  22. <li><a href="#type_generator">Type Generators</a>
  23. <li><a href="#object_generator">Object Generators</a>
  24. <li><a href="#policies">Policies Classes</a>
  25. <li><a href="#adaptors">Adaptors</a>
  26. </ul>
  27. <h2><a name="introduction">Introduction</a></h2>
  28. <p>Generic programming is about generalizing software components
  29. so that they can be easily reused in a wide variety of situations.
  30. In C++, class and function templates are particularly effective
  31. mechanisms for generic programming because they make the
  32. generalization possible without sacrificing efficiency.
  33. <p>As a simple example of generic programming, we will look at how
  34. one might generalize the <tt>memcpy()</tt> function of the
  35. C standard library. An implementation of <tt>memcpy()</tt>
  36. might look like the following:
  37. <p>
  38. <blockquote>
  39. <pre>
  40. void* memcpy(void* region1, const void* region2, size_t n)
  41. {
  42. const char* first = (const char*)region2;
  43. const char* last = ((const char*)region2) + n;
  44. char* result = (char*)region1;
  45. while (first != last)
  46. *result++ = *first++;
  47. return result;
  48. }
  49. </pre>
  50. </blockquote>
  51. The <tt>memcpy()</tt> function is already generalized to some
  52. extent by the use of <tt>void*</tt> so that the function can be
  53. used to copy arrays of different kinds of data. But what if the
  54. data we would like to copy is not in an array? Perhaps it is in a
  55. linked list. Can we generalize the notion of copy to any sequence
  56. of elements? Looking at the body of <tt>memcpy()</tt>, the
  57. function's <b><i>minimal requirements</i></b> are that it needs to
  58. to <i>traverse</i> through the sequence using some sort of
  59. pointer, <i>access</i> elements pointed to, <i>write</i> the
  60. elements to the destination, and <i>compare</i> pointers to know
  61. when to stop. The C++ standard library groups requirements such
  62. as these into <b><i>concepts</i></b>, in this case the <a
  63. href="http://www.sgi.com/tech/stl/InputIterator.html"> Input
  64. Iterator</a> concept (for <tt>region2</tt>) and the <a
  65. href="http://www.sgi.com/tech/stl/OutputIterator.html"> Output
  66. Iterator</a> concept (for <tt>region1</tt>).
  67. <p>If we rewrite the <tt>memcpy()</tt> as a function template, and
  68. use the <a href="http://www.sgi.com/tech/stl/InputIterator.html">
  69. Input Iterator</a> and <a
  70. href="http://www.sgi.com/tech/stl/OutputIterator.html"> Output
  71. Iterator</a> concepts to describe the requirements on the template
  72. parameters, we can implement a highly reusable <tt>copy()</tt>
  73. function in the following way:
  74. <p>
  75. <blockquote>
  76. <pre>
  77. template &lt;typename InputIterator, typename OutputIterator&gt;
  78. OutputIterator
  79. copy(InputIterator first, InputIterator last, OutputIterator result)
  80. {
  81. while (first != last)
  82. *result++ = *first++;
  83. return result;
  84. }
  85. </pre>
  86. </blockquote>
  87. <p>Using the generic <tt>copy()</tt> function, we can now copy
  88. elements from any kind of sequence, including a linked list that
  89. exports iterators such as <tt>std::list</tt>.
  90. <p>
  91. <blockquote>
  92. <pre>
  93. #include &lt;list&gt;
  94. #include &lt;vector&gt;
  95. #include &lt;iostream&gt;
  96. int main()
  97. {
  98. const int N = 3;
  99. std::vector&lt;int&gt; region1(N);
  100. std::list&lt;int&gt; region2;
  101. region2.push_back(1);
  102. region2.push_back(0);
  103. region2.push_back(3);
  104. std::copy(region2.begin(), region2.end(), region1.begin());
  105. for (int i = 0; i &lt; N; ++i)
  106. std::cout &lt;&lt; region1[i] &lt;&lt; " ";
  107. std::cout &lt;&lt; std::endl;
  108. }
  109. </pre>
  110. </blockquote>
  111. <h2><a name="concept">Anatomy of a Concept</a></h2>
  112. A <b><i>concept</i></b> is a set requirements, where the
  113. requirements consist of valid expressions, associated types,
  114. invariants, and complexity guarantees. A type that satisfies the
  115. set of requirements is said to <b><i>model</i></b> the concept. A
  116. concept can extend the requirements of another concept, which is
  117. called <b><i>refinement</i></b>.
  118. <ul>
  119. <li><b>Valid Expressions</b> are C++ expressions which must compile
  120. successfully for the objects involved in the expression to be
  121. considered <i>models</i> of the concept.
  122. <li><b>Associated Types</b> are types that are related to the
  123. modeling type in that they participate in one or more of the
  124. valid expressions. Typically associated types can be accessed
  125. either through typedefs nested within a class definition for
  126. the modeling type, or they are accessed through a <a
  127. href="#traits">traits class</a>.
  128. <li><b>Invariants</b> are run-time characteristics of the
  129. objects that must always be true, that is, the functions involving
  130. the objects must preserve these characteristics. The invariants
  131. often take the form of pre-conditions and post-conditions.
  132. <li><b>Complexity Guarantees</b> are maximum limits on how long
  133. the execution of one of the valid expressions will take, or how
  134. much of various resources its computation will use.
  135. </ul>
  136. <p>The concepts used in the C++ Standard Library are documented at
  137. the <a href="http://www.sgi.com/tech/stl/table_of_contents.html">
  138. SGI STL site</a>.
  139. <h2><a name="traits">Traits</a></h2>
  140. <p>A traits class provides a way of associating information with a
  141. compile-time entity (a type, integral constant, or address). For example,
  142. the class template <tt><a href=
  143. "http://www.sgi.com/tech/stl/iterator_traits.html">std::iterator_traits&lt;T&gt;</a></tt>
  144. looks something like this:
  145. <blockquote>
  146. <pre>
  147. template &lt;class Iterator&gt;
  148. struct iterator_traits {
  149. typedef ... iterator_category;
  150. typedef ... value_type;
  151. typedef ... difference_type;
  152. typedef ... pointer;
  153. typedef ... reference;
  154. };
  155. </pre>
  156. </blockquote>
  157. The traits' <tt>value_type</tt> gives generic code the type which the
  158. iterator is "pointing at", while the <tt>iterator_category</tt> can be used
  159. to select more efficient algorithms depending on the iterator's
  160. capabilities.
  161. <p>A key feature of traits templates is that they're <i>non-intrusive</i>:
  162. they allow us to associate information with arbitrary types, including
  163. built-in types and types defined in third-party libraries, Normally, traits
  164. are specified for a particular type by (partially) specializing the traits
  165. template.
  166. <p>For an in-depth description of <tt>std::iterator_traits</tt>, see <a href=
  167. "http://www.sgi.com/tech/stl/iterator_traits.html">this page</a> provided
  168. by SGI. Another very different expression of the traits idiom in the
  169. standard is <tt>std::numeric_limits&lt;T&gt;</tt> which provides constants
  170. describing the range and capabilities of numeric types.
  171. <h2><a name="tag_dispatching">Tag Dispatching</a></h2>
  172. <p>
  173. A technique that often goes hand in hand with traits classes is
  174. tag dispatching, which is a way of using function overloading to
  175. dispatch based on properties of a type. A good example of this is
  176. the implementation of the <a
  177. href="http://www.sgi.com/tech/stl/advance.html"><tt>std::advance()</tt></a>
  178. function in the C++ Standard Library, which increments an
  179. iterator <tt>n</tt> times. Depending on the kind of iterator,
  180. there are different optimizations that can be applied in the
  181. implementation. If the iterator is <a
  182. href="http://www.sgi.com/tech/stl/RandomAccessIterator.html">random
  183. access</a> (can jump forward and backward arbitrary distances),
  184. then the <tt>advance()</tt> function can simply be implemented
  185. with <tt>i += n</tt>, and is very efficient: constant time. If
  186. the iterator is <a
  187. href="http://www.sgi.com/tech/stl/BidirectionalIterator.html">bidirectional</a>,
  188. then it makes sense for <tt>n</tt> to be negative, we can
  189. decrement the iterator <tt>n</tt> times.
  190. </p>
  191. <p>
  192. The relation between tag dispatching and traits classes is
  193. that the property used for dispatching (in this case the
  194. <tt>iterator_category</tt>) is accessed through a traits class.
  195. The main <tt>advance()</tt> function uses the <a
  196. href="http://www.sgi.com/tech/stl/iterator_traits.html"><tt>iterator_traits</tt></a>
  197. class to get the <tt>iterator_category</tt>. It then makes a call
  198. the the overloaded <tt>advance_dispatch()</tt> function.
  199. The
  200. appropriate <tt>advance_dispatch()</tt> is selected by the
  201. compiler based on whatever type the <tt>iterator_category</tt>
  202. resolves to, either <a
  203. href="http://www.sgi.com/tech/stl/input_iterator_tag.html">
  204. <tt>input_iterator_tag</tt></a>, <a
  205. href="http://www.sgi.com/tech/stl/bidirectional_iterator_tag.html">
  206. <tt>bidirectional_iterator_tag</tt></a>, or <a
  207. href="http://www.sgi.com/tech/stl/random_access_iterator_tag.html">
  208. <tt>random_access_iterator_tag</tt></a>. A <b><i>tag</i></b> is
  209. simply a class whose only purpose is to convey some property for
  210. use in tag dispatching and similar techniques. Refer to <a
  211. href="http://www.sgi.com/tech/stl/iterator_tags.html">this
  212. page</a> for a more detailed description of iterator tags.
  213. </p>
  214. <blockquote>
  215. <pre>
  216. namespace std {
  217. struct input_iterator_tag { };
  218. struct bidirectional_iterator_tag { };
  219. struct random_access_iterator_tag { };
  220. namespace detail {
  221. template &lt;class InputIterator, class Distance&gt;
  222. void advance_dispatch(InputIterator&amp; i, Distance n, <b>input_iterator_tag</b>) {
  223. while (n--) ++i;
  224. }
  225. template &lt;class BidirectionalIterator, class Distance&gt;
  226. void advance_dispatch(BidirectionalIterator&amp; i, Distance n,
  227. <b>bidirectional_iterator_tag</b>) {
  228. if (n &gt;= 0)
  229. while (n--) ++i;
  230. else
  231. while (n++) --i;
  232. }
  233. template &lt;class RandomAccessIterator, class Distance&gt;
  234. void advance_dispatch(RandomAccessIterator&amp; i, Distance n,
  235. <b>random_access_iterator_tag</b>) {
  236. i += n;
  237. }
  238. }
  239. template &lt;class InputIterator, class Distance&gt;
  240. void advance(InputIterator&amp; i, Distance n) {
  241. typename <b>iterator_traits&lt;InputIterator&gt;::iterator_category</b> category;
  242. detail::advance_dispatch(i, n, <b>category</b>);
  243. }
  244. }
  245. </pre>
  246. </blockquote>
  247. <h2><a name="type_generator">Type Generators</a></h2>
  248. <p>A <i>type generator</i> is a template whose only purpose is to
  249. synthesize a single new type based on its template argument(s)<a
  250. href="#1">[1]</a>. The generated type is usually expressed as a
  251. nested typedef named, appropriately <tt>type</tt>. A type
  252. generator is usually used to consolidate a complicated type
  253. expression into a simple one, as in <tt>boost::<a href=
  254. "../libs/utility/filter_iterator.hpp">filter_iterator_generator</a></tt>,
  255. which looks something like this:
  256. <blockquote>
  257. <pre>
  258. template &lt;class Predicate, class Iterator,
  259. class Value = <i>complicated default</i>,
  260. class Reference = <i>complicated default</i>,
  261. class Pointer = <i>complicated default</i>,
  262. class Category = <i>complicated default</i>,
  263. class Distance = <i>complicated default</i>
  264. &gt;
  265. struct filter_iterator_generator {
  266. typedef iterator_adaptor&lt;
  267. Iterator,filter_iterator_policies&lt;Predicate,Iterator&gt;,
  268. Value,Reference,Pointer,Category,Distance&gt; <b>type</b>;
  269. };
  270. </pre>
  271. </blockquote>
  272. <p>Now, that's complicated, but producing an adapted filter iterator is
  273. much easier. You can usually just write:
  274. <blockquote>
  275. <pre>
  276. boost::filter_iterator_generator&lt;my_predicate,my_base_iterator&gt;::type
  277. </pre>
  278. </blockquote>
  279. <h2><a name="object_generator">Object Generators</a></h2>
  280. <p>An <i>object generator</i> is a function template whose only purpose is
  281. to construct a new object out of its arguments. Think of it as a kind of
  282. generic constructor. An object generator may be more useful than a plain
  283. constructor when the exact type to be generated is difficult or impossible
  284. to express and the result of the generator can be passed directly to a
  285. function rather than stored in a variable. Most object generators are named
  286. with the prefix "<tt>make_</tt>", after <tt>std::<a href=
  287. "http://www.sgi.com/tech/stl/pair.html">make_pair</a>(const T&amp;, const U&amp;)</tt>.
  288. <p>Here is an example, using another standard object generator, <tt>std::<a
  289. href=
  290. "http://www.sgi.com/tech/stl/back_insert_iterator.html">back_inserter</a>()</tt>:
  291. <blockquote>
  292. <pre>
  293. // Append the items in [start, finish) to c
  294. template &lt;class Container, class Iterator&gt;
  295. void append_sequence(Container&amp; c, Iterator start, Iterator finish)
  296. {
  297. std::copy(start, finish, <b>std::back_inserter</b>(c));
  298. }
  299. </pre>
  300. </blockquote>
  301. <p>Without using the object generator the example above would look like:
  302. write:
  303. <blockquote>
  304. <pre>
  305. // Append the items in [start, finish) to c
  306. template &lt;class Container, class Iterator&gt;
  307. void append_sequence(Container&amp; c, Iterator start, Iterator finish)
  308. {
  309. std::copy(start, finish, <b>std::back_insert_iterator&lt;Container&gt;</b>(c));
  310. }
  311. </pre>
  312. </blockquote>
  313. <p>As expressions get more complicated the need to reduce the verbosity of
  314. type specification gets more compelling.
  315. <h2><a name="policies">Policies Classes</a></h2>
  316. <p>A policies class is a template parameter used to transmit
  317. behaviors. An example from the standard library is <tt>std::<a
  318. href="http://www.dinkumware.com/htm_cpl/memory.html#allocator">allocator</a></tt>,
  319. which supplies memory management behaviors to standard <a
  320. href="http://www.sgi.com/tech/stl/Container.html">containers</a>.
  321. <p>Policies classes have been explored in detail by <a href=
  322. "mailto:andrewalex@hotmail.com">Andrei Alexandrescu</a> in <a href=
  323. "http://www.cs.ualberta.ca/~hoover/cmput401/XP-Notes/xp-conf/Papers/7_3_Alexandrescu.pdf">
  324. this paper</a>. He writes:
  325. <blockquote>
  326. <p>Policy classes are implementations of punctual design choices. They
  327. are inherited from, or contained within, other classes. They provide
  328. different strategies under the same syntactic interface. A class using
  329. policies is templated having one template parameter for each policy it
  330. uses. This allows the user to select the policies needed.
  331. <p>The power of policy classes comes from their ability to combine
  332. freely. By combining several policy classes in a template class with
  333. multiple parameters, one achieves combinatorial behaviors with a linear
  334. amount of code.
  335. </blockquote>
  336. <p>Andrei's description of policies describe their power as being derived
  337. from their granularity and orthogonality. Boost has probably diluted the
  338. distinction in the <a href="../libs/utility/iterator_adaptors.htm">Iterator
  339. Adaptors</a> library, where we transmit all of an adapted iterator's
  340. behavior in a single policies class. There is precedent for this, however:
  341. <tt><a
  342. href="http://www.dinkumware.com/htm_cpl/string2.html#char_traits">std::char_traits</a></tt>,
  343. despite its name, acts as a policies class that determines the behaviors of
  344. <a
  345. href="http://www.dinkumware.com/htm_cpl/string2.html#basic_string">std::basic_string</a>.
  346. <h2><a name="adaptors">Adaptors</a></h2>
  347. <p>An <i>adaptor</i> is a class template which builds on another type or
  348. types to provide a new interface or behavioral variant. Examples of
  349. standard adaptors are <a href=
  350. "http://www.sgi.com/tech/stl/ReverseIterator.html">std::reverse_iterator</a>,
  351. which adapts an iterator type by reversing its motion upon
  352. increment/decrement, and <a href=
  353. "http://www.sgi.com/tech/stl/stack.html">std::stack</a>, which adapts a
  354. container to provide a simple stack interface.
  355. <p>A more comprehensive review of the adaptors in the standard can be found
  356. <a href=
  357. "http://www.cs.rpi.edu/~wiseb/xrds/ovp2-3b.html#SECTION00015000000000000000">
  358. here</a>.
  359. <h2>Notes</h2>
  360. <a name="1">[1]</a> Type generators are a workaround for the lack
  361. of ``templated typedefs'' in C++.
  362. <hr>
  363. <p>Revised
  364. <!--webbot bot="Timestamp" s-type="EDITED" s-format="%d %b %Y" startspan -->12 Feb 2001<!--webbot bot="Timestamp" endspan i-checksum="14377" -->
  365. <p>&copy; Copyright David Abrahams 2001. Permission to copy, use, modify,
  366. sell and distribute this document is granted provided this copyright notice
  367. appears in all copies. This document is provided "as is" without express or
  368. implied warranty, and with no claim as to its suitability for any purpose.
  369. <!-- LocalWords: HTML html charset gif alt htm struct SGI namespace std libs
  370. -->
  371. <!-- LocalWords: InputIterator BidirectionalIterator RandomAccessIterator pdf
  372. -->
  373. <!-- LocalWords: typename Alexandrescu templated Andrei's Abrahams memcpy int
  374. -->
  375. </body>
  376. </html>
  377. <!-- LocalWords: const OutputIterator iostream pre cpl
  378. -->
粤ICP备19079148号