tuple_users_guide.qbk 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. [/
  2. / Copyright (c) 2001 Jaakko Järvi
  3. /
  4. / Distributed under the Boost Software License, Version 1.0. (See
  5. / accompanying file LICENSE_1_0.txt or copy at
  6. / http://www.boost.org/LICENSE_1_0.txt)
  7. /]
  8. [library Boost.Tuple
  9. [quickbook 1.6]
  10. [id tuple]
  11. [copyright 2001 Jaakko J\u00E4rvi]
  12. [dirname tuple]
  13. [license Distributed under the
  14. [@http://boost.org/LICENSE_1_0.txt Boost Software License,
  15. Version 1.0].
  16. ]
  17. ]
  18. [include tuple_advanced_interface.qbk]
  19. [include design_decisions_rationale.qbk]
  20. [template simplesect[title]
  21. [block '''<simplesect><title>'''[title]'''</title>''']]
  22. [template endsimplesect[]
  23. [block '''</simplesect>''']]
  24. A tuple (or n-tuple) is a fixed size collection of elements. Pairs, triples,
  25. quadruples etc. are tuples. In a programming language, a tuple is a data
  26. object containing other objects as elements. These element objects may be of
  27. different types.
  28. Tuples are convenient in many circumstances. For instance, tuples make it easy
  29. to define functions that return more than one value.
  30. Some programming languages, such as ML, Python and Haskell, have built-in
  31. tuple constructs. Unfortunately C++ does not. To compensate for this
  32. "deficiency", the Boost Tuple Library implements a tuple construct using
  33. templates.
  34. [section:using_library Using the Library]
  35. To use the library, just include:
  36. #include "boost/tuple/tuple.hpp"
  37. Comparison operators can be included with:
  38. #include "boost/tuple/tuple_comparison.hpp"
  39. To use tuple input and output operators,
  40. #include "boost/tuple/tuple_io.hpp"
  41. Both `tuple_io.hpp` and `tuple_comparison.hpp` include `tuple.hpp`.
  42. All definitions are in namespace `::boost::tuples`, but the most common names
  43. are lifted to namespace `::boost` with using declarations. These names are:
  44. `tuple`, `make_tuple`, `tie` and `get`. Further, `ref` and `cref` are defined
  45. directly under the `::boost` namespace.
  46. [endsect]
  47. [section:tuple_types Tuple Types]
  48. A tuple type is an instantiation of the `tuple` template. The template
  49. parameters specify the types of the tuple elements. The current version
  50. supports tuples with 0-10 elements. If necessary, the upper limit can be
  51. increased up to, say, a few dozen elements. The data element can be any C++
  52. type. Note that `void` and plain function types are valid C++ types, but
  53. objects of such types cannot exist. Hence, if a tuple type contains such types
  54. as elements, the tuple type can exist, but not an object of that type. There
  55. are natural limitations for element types that cannot be copied, or that are
  56. not default constructible (see [link tuple.constructing_tuples 'Constructing tuples']
  57. below).
  58. For example, the following definitions are valid tuple instantiations (`A`,
  59. `B` and `C` are some user defined classes):
  60. tuple<int>
  61. tuple<double&, const double&, const double, double*, const double*>
  62. tuple<A, int(*)(char, int), B(A::*)(C&), C>
  63. tuple<std::string, std::pair<A, B> >
  64. tuple<A*, tuple<const A*, const B&, C>, bool, void*>
  65. [endsect]
  66. [section:constructing_tuples Constructing Tuples]
  67. The tuple constructor takes the tuple elements as arguments. For an /n/-
  68. element tuple, the constructor can be invoked with /k/ arguments, where
  69. `0` <= /k/ <= /n/. For example:
  70. tuple<int, double>()
  71. tuple<int, double>(1)
  72. tuple<int, double>(1, 3.14)
  73. If no initial value for an element is provided, it is default initialized
  74. (and hence must be default initializable). For example:
  75. class X {
  76. X();
  77. public:
  78. X(std::string);
  79. };
  80. tuple<X,X,X>() // error: no default constructor for X
  81. tuple<X,X,X>(string("Jaba"), string("Daba"), string("Duu")) // ok
  82. In particular, reference types do not have a default initialization:
  83. tuple<double&>() // error: reference must be
  84. // initialized explicitly
  85. double d = 5;
  86. tuple<double&>(d) // ok
  87. tuple<double&>(d+3.14) // error: cannot initialize
  88. // non-const reference with a temporary
  89. tuple<const double&>(d+3.14) // ok, but dangerous:
  90. // the element becomes a dangling reference
  91. Using an initial value for an element that cannot be copied, is a compile time
  92. error:
  93. class Y {
  94. Y(const Y&);
  95. public:
  96. Y();
  97. };
  98. char a[10];
  99. tuple<char[10], Y>(a, Y()); // error, neither arrays nor Y can be copied
  100. tuple<char[10], Y>(); // ok
  101. Note particularly that the following is perfectly ok:
  102. Y y;
  103. tuple<char(&)[10], Y&>(a, y);
  104. It is possible to come up with a tuple type that cannot be constructed. This
  105. occurs if an element that cannot be initialized has a lower index than an
  106. element that requires initialization. For example: `tuple<char[10], int&>`.
  107. In sum, the tuple construction is semantically just a group of individual
  108. elementary constructions.
  109. [section:make_tuple The `make_tuple` function]
  110. Tuples can also be constructed using the `make_tuple` (cf. `std::make_pair`)
  111. helper functions. This makes the construction more convenient, saving the
  112. programmer from explicitly specifying the element types:
  113. tuple<int, int, double> add_multiply_divide(int a, int b) {
  114. return make_tuple(a+b, a*b, double(a)/double(b));
  115. }
  116. By default, the element types are deduced to the plain non-reference types.
  117. E.g.:
  118. void foo(const A& a, B& b) {
  119. ...
  120. make_tuple(a, b);
  121. The `make_tuple` invocation results in a tuple of type `tuple<A, B>`.
  122. Sometimes the plain non-reference type is not desired, e.g. if the element
  123. type cannot be copied. Therefore, the programmer can control the type
  124. deduction and state that a reference to const or reference to non-const type
  125. should be used as the element type instead. This is accomplished with two
  126. helper template functions: [@boost:/libs/core/doc/html/core/ref.html `boost::ref`]
  127. and [@boost:/libs/core/doc/html/core/ref.html `boost::cref`]. Any argument can
  128. be wrapped with these functions to get the desired type. The mechanism does
  129. not compromise const correctness since a const object wrapped with ref results
  130. in a tuple element with const reference type (see the fifth example below).
  131. For example:
  132. A a; B b; const A ca = a;
  133. make_tuple(cref(a), b); // creates tuple<const A&, B>
  134. make_tuple(ref(a), b); // creates tuple<A&, B>
  135. make_tuple(ref(a), cref(b)); // creates tuple<A&, const B&>
  136. make_tuple(cref(ca)); // creates tuple<const A&>
  137. make_tuple(ref(ca)); // creates tuple<const A&>
  138. Array arguments to `make_tuple` functions are deduced to reference to const
  139. types by default; there is no need to wrap them with `cref`. For example:
  140. make_tuple("Donald", "Daisy");
  141. This creates an object of type `tuple<const char (&)[7], const char (&)[6]>`
  142. (note that the type of a string literal is an array of const characters, not
  143. `const char*`). However, to get `make_tuple` to create a tuple with an element
  144. of a non-const array type one must use the `ref` wrapper.
  145. Function pointers are deduced to the plain non-reference type, that is, to
  146. plain function pointer. A tuple can also hold a reference to a function, but
  147. such a tuple cannot be constructed with `make_tuple` (a const qualified
  148. function type would result, which is illegal):
  149. void f(int i);
  150. ...
  151. make_tuple(&f); // tuple<void (*)(int)>
  152. ...
  153. tuple<tuple<void (&)(int)> > a(f) // ok
  154. make_tuple(f); // not ok
  155. [endsect]
  156. [endsect]
  157. [section:accessing_elements Accessing Tuple Elements]
  158. Tuple elements are accessed with the expression:
  159. t.get<N>()
  160. or
  161. get<N>(t)
  162. where `t` is a tuple object and `N` is a constant integral expression
  163. specifying the index of the element to be accessed. Depending on whether `t`
  164. is const or not, `get` returns the `N`-th element as a reference to const or
  165. non-const type. The index of the first element is `0` and thus `N` must be
  166. between `0` and /k/`-1`, where /k/ is the number of elements in the tuple.
  167. Violations of these constraints are detected at compile time. Examples:
  168. double d = 2.7; A a;
  169. tuple<int, double&, const A&> t(1, d, a);
  170. const tuple<int, double&, const A&> ct = t;
  171. ...
  172. int i = get<0>(t); i = t.get<0>(); // ok
  173. int j = get<0>(ct); // ok
  174. get<0>(t) = 5; // ok
  175. get<0>(ct) = 5; // error, can't assign to const
  176. ...
  177. double e = get<1>(t); // ok
  178. get<1>(t) = 3.14; // ok
  179. get<2>(t) = A(); // error, can't assign to const
  180. A aa = get<3>(t); // error: index out of bounds
  181. ...
  182. ++get<0>(t); // ok, can be used as any variable
  183. /[Note:/ The member `get` functions are not supported with MS Visual C++
  184. compiler. Further, the compiler has trouble with finding the non-member `get`
  185. functions without an explicit namespace qualifier. Hence, all `get` calls
  186. should be qualified as `tuples::get<N>(a_tuple)` when writing code that should
  187. compile with MSVC++ 6.0./]/
  188. [endsect]
  189. [section:construction_and_assignment Copy Construction and Tuple Assignment]
  190. A tuple can be copy constructed from another tuple, provided that the element
  191. types are element-wise copy constructible. Analogously, a tuple can be
  192. assigned to another tuple, provided that the element types are element-wise
  193. assignable. For example:
  194. class A {};
  195. class B : public A {};
  196. struct C { C(); C(const B&); };
  197. struct D { operator C() const; };
  198. tuple<char, B*, B, D> t;
  199. ...
  200. tuple<int, A*, C, C> a(t); // ok
  201. a = t; // ok
  202. In both cases, the conversions performed are:
  203. * `char -> int`,
  204. * `B* -> A*` (derived class pointer to base class pointer),
  205. * `B -> C` (a user defined conversion), and
  206. * `D -> C` (a user defined conversion).
  207. Note that assignment is also defined from `std::pair` types:
  208. tuple<float, int> a = std::make_pair(1, 'a');
  209. [endsect]
  210. [section:relational_operators Relational Operators]
  211. Tuples reduce the operators `==`, `!=`, `<`, `>`, `<=` and `>=` to the
  212. corresponding elementary operators. This means, that if any of these operators
  213. is defined between all elements of two tuples, then the same operator is
  214. defined between the tuples as well. The equality operators for two tuples `a`
  215. and `b` are defined as:
  216. * `a == b` iff for each `i`: `a`'''<subscript>i</subscript>'''` == b`'''<subscript>i</subscript>'''
  217. * `a != b` iff exists `i`: `a`'''<subscript>i</subscript>'''` != b`'''<subscript>i</subscript>'''
  218. The operators `<`, `>`, `<=` and `>=` implement a lexicographical ordering.
  219. Note that an attempt to compare two tuples of different lengths results in a
  220. compile time error. Also, the comparison operators are /"short-circuited"/:
  221. elementary comparisons start from the first elements and are performed only
  222. until the result is clear.
  223. Examples:
  224. tuple<std::string, int, A> t1(std::string("same?"), 2, A());
  225. tuple<std::string, long, A> t2(std::string("same?"), 2, A());
  226. tuple<std::string, long, A> t3(std::string("different"), 3, A());
  227. bool operator==(A, A) { std::cout << "All the same to me..."; return true; }
  228. t1 == t2; // true
  229. t1 == t3; // false, does not print "All the..."
  230. [endsect]
  231. [section:tiers Tiers]
  232. /Tiers/ are tuples, where all elements are of non-const reference types. They
  233. are constructed with a call to the `tie` function template (cf. `make_tuple`):
  234. int i; char c; double d;
  235. ...
  236. tie(i, c, a);
  237. The above `tie` function creates a tuple of type `tuple<int&, char&, double&>`.
  238. The same result could be achieved with the call `make_tuple(ref(i), ref(c), ref(a))`.
  239. A tuple that contains non-const references as elements can be used to 'unpack'
  240. another tuple into variables. E.g.:
  241. int i; char c; double d;
  242. tie(i, c, d) = make_tuple(1,'a', 5.5);
  243. std::cout << i << " " << c << " " << d;
  244. This code prints `1 a 5.5` to the standard output stream. A tuple unpacking
  245. operation like this is found for example in ML and Python. It is convenient
  246. when calling functions which return tuples.
  247. The tying mechanism works with `std::pair` templates as well:
  248. int i; char c;
  249. tie(i, c) = std::make_pair(1, 'a');
  250. [section Ignore]
  251. There is also an object called `ignore` which allows you to ignore an element
  252. assigned by a tuple. The idea is that a function may return a tuple, only part
  253. of which you are interested in. For example (note, that ignore is under the
  254. `tuples` subnamespace):
  255. char c;
  256. tie(tuples::ignore, c) = std::make_pair(1, 'a');
  257. [endsect]
  258. [endsect]
  259. [section:streaming Streaming]
  260. The global `operator<<` has been overloaded for `std::ostream` such that
  261. tuples are output by recursively calling `operator<<` for each element.
  262. Analogously, the global `operator>>` has been overloaded to extract tuples
  263. from `std::istream` by recursively calling `operator>>` for each element.
  264. The default delimiter between the elements is space, and the tuple is enclosed
  265. in parenthesis. For Example:
  266. tuple<float, int, std::string> a(1.0f, 2, std::string("Howdy folks!");
  267. cout << a;
  268. outputs the tuple as: `(1.0 2 Howdy folks!)`
  269. The library defines three manipulators for changing the default behavior:
  270. * `set_open(char)` defines the character that is output before the first element.
  271. * `set_close(char)` defines the character that is output after the last element.
  272. * `set_delimiter(char)` defines the delimiter character between elements.
  273. Note, that these manipulators are defined in the tuples subnamespace. For
  274. example:
  275. cout << tuples::set_open('[') << tuples::set_close(']') << tuples::set_delimiter(',') << a;
  276. outputs the same tuple `a` as: `[1.0,2,Howdy folks!]`
  277. The same manipulators work with `operator>>` and `istream` as well. Suppose
  278. the `cin` stream contains the following data:
  279. (1 2 3) [4:5]
  280. The code:
  281. tuple<int, int, int> i;
  282. tuple<int, int> j;
  283. cin >> i;
  284. cin >> tuples::set_open('[') >> tuples::set_close(']') >> tuples::set_delimiter(':');
  285. cin >> j;
  286. reads the data into the tuples `i` and `j`.
  287. Note that extracting tuples with `std::string` or C-style string elements does
  288. not generally work, since the streamed tuple representation may not be
  289. unambiguously parseable.
  290. [endsect]
  291. [section:performance Performance]
  292. All tuple access and construction functions are small inlined one-liners.
  293. Therefore, a decent compiler can eliminate any extra cost of using tuples
  294. compared to using hand-written tuple like classes. Particularly, with a decent
  295. compiler there is no performance difference between this code:
  296. class hand_made_tuple {
  297. A a; B b; C c;
  298. public:
  299. hand_made_tuple(const A& aa, const B& bb, const C& cc)
  300. : a(aa), b(bb), c(cc) {};
  301. A& getA() { return a; };
  302. B& getB() { return b; };
  303. C& getC() { return c; };
  304. };
  305. hand_made_tuple hmt(A(), B(), C());
  306. hmt.getA(); hmt.getB(); hmt.getC();
  307. and this code:
  308. tuple<A, B, C> t(A(), B(), C());
  309. t.get<0>(); t.get<1>(); t.get<2>();
  310. Note, that there are widely used compilers (e.g. bcc 5.5.1) which fail to
  311. optimize this kind of tuple usage.
  312. Depending on the optimizing ability of the compiler, the tier mechanism may
  313. have a small performance penalty compared to using non-const reference
  314. parameters as a mechanism for returning multiple values from a function. For
  315. example, suppose that the following functions `f1` and `f2` have equivalent
  316. functionalities:
  317. void f1(int&, double&);
  318. tuple<int, double> f2();
  319. Then, the call #1 may be slightly faster than #2 in the code below:
  320. int i; double d;
  321. ...
  322. f1(i,d); // #1
  323. tie(i,d) = f2(); // #2
  324. See [[link publ_1 1], [link publ_2 2]] for more in-depth discussions about
  325. efficiency.
  326. [section Effect on Compile Time]
  327. Compiling tuples can be slow due to the excessive amount of template
  328. instantiations. Depending on the compiler and the tuple length, it may be more
  329. than 10 times slower to compile a tuple construct, compared to compiling an
  330. equivalent explicitly written class, such as the `hand_made_tuple` class above.
  331. However, as a realistic program is likely to contain a lot of code in addition
  332. to tuple definitions, the difference is probably unnoticeable. Compile time
  333. increases between 5 and 10 percent were measured for programs which used tuples
  334. very frequently. With the same test programs, memory consumption of compiling
  335. increased between 22% to 27%. See [[link publ_1 1], [link publ_2 2]] for
  336. details.
  337. [endsect]
  338. [endsect]
  339. [section:portability Portability]
  340. The library code is(?) standard C++ and thus the library works with a standard
  341. conforming compiler. Below is a list of compilers and known problems with each
  342. compiler:
  343. [table
  344. [[Compiler] [Problems]]
  345. [[gcc 2.95] [-]]
  346. [[edg 2.44] [-]]
  347. [[Borland 5.5] [Can't use function pointers or member pointers as
  348. tuple elements]]
  349. [[Metrowerks 6.2] [Can't use `ref` and `cref` wrappers]]
  350. [[MS Visual C++] [No reference elements (`tie` still works). Can't use
  351. `ref` and `cref` wrappers]]
  352. ]
  353. [endsect]
  354. [section:more_details More Details]
  355. [link tuple_advanced_interface Advanced features] (describes some metafunctions etc.).
  356. [link design_decisions_rationale Rationale behind some design/implementation decisions].
  357. [endsect]
  358. [section:thanks Acknowledgements]
  359. Gary Powell has been an indispensable helping hand. In particular, stream
  360. manipulators for tuples were his idea. Doug Gregor came up with a working
  361. version for MSVC, David Abrahams found a way to get rid of most of the
  362. restrictions for compilers not supporting partial specialization. Thanks to
  363. Jeremy Siek, William Kempf and Jens Maurer for their help and suggestions. The
  364. comments by Vesa Karvonen, John Max Skaller, Ed Brey, Beman Dawes, David
  365. Abrahams and Hartmut Kaiser helped to improve the library. The idea for the
  366. `tie` mechanism came from an old usenet article by Ian McCulloch, where he
  367. proposed something similar for `std::pair`s.
  368. [endsect]
  369. [section:references References]
  370. [#publ_1]
  371. [1] J\u00E4rvi J.: /Tuples and multiple return values in C++/, TUCS Technical Report No 249, 1999.
  372. [#publ_2]
  373. [2] J\u00E4rvi J.: /ML-Style Tuple Assignment in Standard C++ - Extending the Multiple Return Value Formalism/, TUCS Technical Report No 267, 1999.
  374. [#publ_3]
  375. [3] J\u00E4rvi J.: /Tuple Types and Multiple Return Values/, C/C++ Users Journal, August 2001.
  376. [endsect]