• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
2<html>
3<head>
4<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
5<title>Chapter 15. Boost.Foreach</title>
6<link rel="stylesheet" href="../../doc/src/boostbook.css" type="text/css">
7<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
8<link rel="home" href="index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
9<link rel="up" href="libraries.html" title="Part I. The Boost C++ Libraries (BoostBook Subset)">
10<link rel="prev" href="boost_dll/acknowledgements.html" title="Acknowledgements">
11<link rel="next" href="foreach/extensibility.html" title="Extensibility">
12</head>
13<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
14<table cellpadding="2" width="100%"><tr>
15<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../boost.png"></td>
16<td align="center"><a href="../../index.html">Home</a></td>
17<td align="center"><a href="../../libs/libraries.htm">Libraries</a></td>
18<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
19<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
20<td align="center"><a href="../../more/index.htm">More</a></td>
21</tr></table>
22<hr>
23<div class="spirit-nav">
24<a accesskey="p" href="boost_dll/acknowledgements.html"><img src="../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="libraries.html"><img src="../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="index.html"><img src="../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="foreach/extensibility.html"><img src="../../doc/src/images/next.png" alt="Next"></a>
25</div>
26<div class="chapter">
27<div class="titlepage"><div>
28<div><h2 class="title">
29<a name="foreach"></a>Chapter 15. Boost.Foreach</h2></div>
30<div><div class="author"><h3 class="author">
31<span class="firstname">Eric</span> <span class="surname">Niebler</span>
32</h3></div></div>
33<div><p class="copyright">Copyright © 2004 Eric Niebler</p></div>
34<div><div class="legalnotice">
35<a name="foreach.legal"></a><p>
36        Distributed under the Boost Software License, Version 1.0. (See accompanying
37        file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
38      </p>
39</div></div>
40</div></div>
41<div class="toc">
42<p><b>Table of Contents</b></p>
43<dl class="toc">
44<dt><span class="section"><a href="foreach.html#foreach.introduction">Introduction</a></span></dt>
45<dt><span class="section"><a href="foreach/extensibility.html">Extensibility</a></span></dt>
46<dt><span class="section"><a href="foreach/portability.html">Portability</a></span></dt>
47<dt><span class="section"><a href="foreach/pitfalls.html">Pitfalls</a></span></dt>
48<dt><span class="section"><a href="foreach/history_and_acknowledgements.html">History and Acknowledgements</a></span></dt>
49</dl>
50</div>
51<div class="section">
52<div class="titlepage"><div><div><h2 class="title" style="clear: both">
53<a name="foreach.introduction"></a><a class="link" href="foreach.html#foreach.introduction" title="Introduction">Introduction</a>
54</h2></div></div></div>
55<div class="blockquote"><blockquote class="blockquote"><p>
56        <span class="quote">“<span class="quote">Make simple things easy.</span>”</span><br> <span class="bold"><strong><span class="emphasis"><em>--
57        Larry Wall</em></span></strong></span>
58      </p></blockquote></div>
59<h3>
60<a name="foreach.introduction.h0"></a>
61      <span class="phrase"><a name="foreach.introduction.what_is__literal_boost_foreach__literal__"></a></span><a class="link" href="foreach.html#foreach.introduction.what_is__literal_boost_foreach__literal__">What
62      is <code class="literal">BOOST_FOREACH</code>?</a>
63    </h3>
64<p>
65      In C++, writing a loop that iterates over a sequence is tedious. We can either
66      use iterators, which requires a considerable amount of boiler-plate, or we
67      can use the <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">for_each</span><span class="special">()</span></code>
68      algorithm and move our loop body into a predicate, which requires no less boiler-plate
69      and forces us to move our logic far from where it will be used. In contrast,
70      some other languages, like Perl, provide a dedicated "foreach" construct
71      that automates this process. <code class="literal">BOOST_FOREACH</code> is just such
72      a construct for C++. It iterates over sequences for us, freeing us from having
73      to deal directly with iterators or write predicates.
74    </p>
75<p>
76      <code class="literal">BOOST_FOREACH</code> is designed for ease-of-use and efficiency.
77      It does no dynamic allocations, makes no virtual function calls or calls through
78      function pointers, and makes no calls that are not transparent to the compiler's
79      optimizer. This results in near-optimal code generation; the performance of
80      <code class="literal">BOOST_FOREACH</code> is usually within a few percent of the equivalent
81      hand-coded loop. And although <code class="literal">BOOST_FOREACH</code> is a macro,
82      it is a remarkably well-behaved one. It evaluates its arguments exactly once,
83      leading to no nasty surprises.
84    </p>
85<h3>
86<a name="foreach.introduction.h1"></a>
87      <span class="phrase"><a name="foreach.introduction.hello__world_"></a></span><a class="link" href="foreach.html#foreach.introduction.hello__world_">Hello,
88      world!</a>
89    </h3>
90<p>
91      Below is a sample program that uses <code class="literal">BOOST_FOREACH</code> to loop
92      over the contents of a <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span></code>.
93    </p>
94<pre class="programlisting"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">string</span><span class="special">&gt;</span>
95<span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">iostream</span><span class="special">&gt;</span>
96<span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">foreach</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span>
97
98<span class="keyword">int</span> <span class="identifier">main</span><span class="special">()</span>
99<span class="special">{</span>
100    <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span> <span class="identifier">hello</span><span class="special">(</span> <span class="string">"Hello, world!"</span> <span class="special">);</span>
101
102    <span class="identifier">BOOST_FOREACH</span><span class="special">(</span> <span class="keyword">char</span> <span class="identifier">ch</span><span class="special">,</span> <span class="identifier">hello</span> <span class="special">)</span>
103    <span class="special">{</span>
104        <span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="identifier">ch</span><span class="special">;</span>
105    <span class="special">}</span>
106
107    <span class="keyword">return</span> <span class="number">0</span><span class="special">;</span>
108<span class="special">}</span>
109</pre>
110<p>
111      This program outputs the following:
112    </p>
113<pre class="programlisting">Hello, world!
114</pre>
115<h3>
116<a name="foreach.introduction.h2"></a>
117      <span class="phrase"><a name="foreach.introduction.supported_sequence_types"></a></span><a class="link" href="foreach.html#foreach.introduction.supported_sequence_types">Supported
118      Sequence Types</a>
119    </h3>
120<p>
121      <code class="literal">BOOST_FOREACH</code> iterates over sequences. But what qualifies
122      as a sequence, exactly? Since <code class="literal">BOOST_FOREACH</code> is built on
123      top of <a href="../../libs/range/index.html" target="_top">Boost.Range</a>, it automatically
124      supports those types which <a href="../../libs/range/index.html" target="_top">Boost.Range</a>
125      recognizes as sequences. Specifically, <code class="literal">BOOST_FOREACH</code> works
126      with types that satisfy the <a href="../../libs/range/doc/html/range/concepts/single_pass_range.html" target="_top">Single
127      Pass Range Concept</a>. For example, we can use <code class="literal">BOOST_FOREACH</code>
128      with:
129    </p>
130<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
131<li class="listitem">
132          STL containers
133        </li>
134<li class="listitem">
135          arrays
136        </li>
137<li class="listitem">
138          Null-terminated strings (<code class="computeroutput"><span class="keyword">char</span></code>
139          and <code class="computeroutput"><span class="keyword">wchar_t</span></code>)
140        </li>
141<li class="listitem">
142          std::pair of iterators
143        </li>
144</ul></div>
145<div class="note"><table border="0" summary="Note">
146<tr>
147<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="../../doc/src/images/note.png"></td>
148<th align="left">Note</th>
149</tr>
150<tr><td align="left" valign="top"><p>
151        The support for STL containers is very general; anything that looks like
152        an STL container counts. If it has nested <code class="computeroutput"><span class="identifier">iterator</span></code>
153        and <code class="computeroutput"><span class="identifier">const_iterator</span></code> types
154        and <code class="computeroutput"><span class="identifier">begin</span><span class="special">()</span></code>
155        and <code class="computeroutput"><span class="identifier">end</span><span class="special">()</span></code>
156        member functions, <code class="literal">BOOST_FOREACH</code> will automatically know
157        how to iterate over it. It is in this way that <a href="../../libs/range/doc/html/range/reference/utilities/iterator_range.html" target="_top"><code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">iterator_range</span><span class="special">&lt;&gt;</span></code></a>
158        and <a href="../../libs/range/doc/html/range/reference/utilities/sub_range.html" target="_top"><code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">sub_range</span><span class="special">&lt;&gt;</span></code></a>
159        work with <code class="literal">BOOST_FOREACH</code>.
160      </p></td></tr>
161</table></div>
162<p>
163      See the section on <a class="link" href="foreach/extensibility.html" title="Extensibility">Extensibility</a>
164      to find out how to make <code class="literal">BOOST_FOREACH</code> work with other types.
165    </p>
166<h3>
167<a name="foreach.introduction.h3"></a>
168      <span class="phrase"><a name="foreach.introduction.examples"></a></span><a class="link" href="foreach.html#foreach.introduction.examples">Examples</a>
169    </h3>
170<p>
171      Below are some examples that demonstrate all the different ways we can use
172      <code class="literal">BOOST_FOREACH</code>.
173    </p>
174<p>
175      Iterate over an STL container:
176    </p>
177<pre class="programlisting"><span class="identifier">std</span><span class="special">::</span><span class="identifier">list</span><span class="special">&lt;</span><span class="keyword">int</span><span class="special">&gt;</span> <span class="identifier">list_int</span><span class="special">(</span> <span class="comment">/*...*/</span> <span class="special">);</span>
178<span class="identifier">BOOST_FOREACH</span><span class="special">(</span> <span class="keyword">int</span> <span class="identifier">i</span><span class="special">,</span> <span class="identifier">list_int</span> <span class="special">)</span>
179<span class="special">{</span>
180    <span class="comment">// do something with i</span>
181<span class="special">}</span>
182</pre>
183<p>
184      Iterate over an array, with covariance (i.e., the type of the iteration variable
185      is not exactly the same as the element type of the container):
186    </p>
187<pre class="programlisting"><span class="keyword">short</span> <span class="identifier">array_short</span><span class="special">[]</span> <span class="special">=</span> <span class="special">{</span><span class="number">1</span><span class="special">,</span><span class="number">2</span><span class="special">,</span><span class="number">3</span><span class="special">};</span>
188<span class="identifier">BOOST_FOREACH</span><span class="special">(</span> <span class="keyword">int</span> <span class="identifier">i</span><span class="special">,</span> <span class="identifier">array_short</span> <span class="special">)</span>
189<span class="special">{</span>
190    <span class="comment">// The short was implicitly converted to an int</span>
191<span class="special">}</span>
192</pre>
193<p>
194      Predeclare the loop variable, and use <code class="computeroutput"><span class="keyword">break</span></code>,
195      <code class="computeroutput"><span class="keyword">continue</span></code>, and <code class="computeroutput"><span class="keyword">return</span></code>
196      in the loop body:
197    </p>
198<pre class="programlisting"><span class="identifier">std</span><span class="special">::</span><span class="identifier">deque</span><span class="special">&lt;</span><span class="keyword">int</span><span class="special">&gt;</span> <span class="identifier">deque_int</span><span class="special">(</span> <span class="comment">/*...*/</span> <span class="special">);</span>
199<span class="keyword">int</span> <span class="identifier">i</span> <span class="special">=</span> <span class="number">0</span><span class="special">;</span>
200<span class="identifier">BOOST_FOREACH</span><span class="special">(</span> <span class="identifier">i</span><span class="special">,</span> <span class="identifier">deque_int</span> <span class="special">)</span>
201<span class="special">{</span>
202    <span class="keyword">if</span><span class="special">(</span> <span class="identifier">i</span> <span class="special">==</span> <span class="number">0</span> <span class="special">)</span> <span class="keyword">return</span><span class="special">;</span>
203    <span class="keyword">if</span><span class="special">(</span> <span class="identifier">i</span> <span class="special">==</span> <span class="number">1</span> <span class="special">)</span> <span class="keyword">continue</span><span class="special">;</span>
204    <span class="keyword">if</span><span class="special">(</span> <span class="identifier">i</span> <span class="special">==</span> <span class="number">2</span> <span class="special">)</span> <span class="keyword">break</span><span class="special">;</span>
205<span class="special">}</span>
206</pre>
207<p>
208      Iterate over a sequence by reference, and modify the underlying sequence:
209    </p>
210<pre class="programlisting"><span class="keyword">short</span> <span class="identifier">array_short</span><span class="special">[]</span> <span class="special">=</span> <span class="special">{</span> <span class="number">1</span><span class="special">,</span> <span class="number">2</span><span class="special">,</span> <span class="number">3</span> <span class="special">};</span>
211<span class="identifier">BOOST_FOREACH</span><span class="special">(</span> <span class="keyword">short</span> <span class="special">&amp;</span> <span class="identifier">i</span><span class="special">,</span> <span class="identifier">array_short</span> <span class="special">)</span>
212<span class="special">{</span>
213    <span class="special">++</span><span class="identifier">i</span><span class="special">;</span>
214<span class="special">}</span>
215<span class="comment">// array_short contains {2,3,4} here</span>
216</pre>
217<p>
218      Iterate over a vector of vectors with nested <code class="literal">BOOST_FOREACH</code>
219      loops. In this example, notice that braces around the loop body are not necessary:
220    </p>
221<pre class="programlisting"><span class="identifier">std</span><span class="special">::</span><span class="identifier">vector</span><span class="special">&lt;</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">vector</span><span class="special">&lt;</span><span class="keyword">int</span><span class="special">&gt;</span> <span class="special">&gt;</span> <span class="identifier">matrix_int</span><span class="special">;</span>
222<span class="identifier">BOOST_FOREACH</span><span class="special">(</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">vector</span><span class="special">&lt;</span><span class="keyword">int</span><span class="special">&gt;</span> <span class="special">&amp;</span> <span class="identifier">row</span><span class="special">,</span> <span class="identifier">matrix_int</span> <span class="special">)</span>
223    <span class="identifier">BOOST_FOREACH</span><span class="special">(</span> <span class="keyword">int</span> <span class="special">&amp;</span> <span class="identifier">i</span><span class="special">,</span> <span class="identifier">row</span> <span class="special">)</span>
224        <span class="special">++</span><span class="identifier">i</span><span class="special">;</span>
225</pre>
226<p>
227      Iterate over an expression that returns a sequence by value (i.e. an rvalue):
228    </p>
229<pre class="programlisting"><span class="keyword">extern</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">vector</span><span class="special">&lt;</span><span class="keyword">float</span><span class="special">&gt;</span> <span class="identifier">get_vector_float</span><span class="special">();</span>
230<span class="identifier">BOOST_FOREACH</span><span class="special">(</span> <span class="keyword">float</span> <span class="identifier">f</span><span class="special">,</span> <span class="identifier">get_vector_float</span><span class="special">()</span> <span class="special">)</span>
231<span class="special">{</span>
232    <span class="comment">// Note: get_vector_float() will be called exactly once</span>
233<span class="special">}</span>
234</pre>
235<p>
236      Iterate in reverse:
237    </p>
238<pre class="programlisting"><span class="identifier">std</span><span class="special">::</span><span class="identifier">list</span><span class="special">&lt;</span><span class="keyword">int</span><span class="special">&gt;</span> <span class="identifier">list_int</span><span class="special">(</span> <span class="comment">/*...*/</span> <span class="special">);</span>
239<span class="identifier">BOOST_REVERSE_FOREACH</span><span class="special">(</span> <span class="keyword">int</span> <span class="identifier">i</span><span class="special">,</span> <span class="identifier">list_int</span> <span class="special">)</span>
240<span class="special">{</span>
241    <span class="comment">// do something with i</span>
242<span class="special">}</span>
243</pre>
244<p>
245      Iterating over rvalues doesn't work on some older compilers. Check the <a class="link" href="foreach/portability.html" title="Portability">Portability</a> section to see whether your
246      compiler supports this.
247    </p>
248<h3>
249<a name="foreach.introduction.h4"></a>
250      <span class="phrase"><a name="foreach.introduction.making__literal_boost_foreach__literal__prettier"></a></span><a class="link" href="foreach.html#foreach.introduction.making__literal_boost_foreach__literal__prettier">Making
251      <code class="literal">BOOST_FOREACH</code> Prettier</a>
252    </h3>
253<p>
254      People have complained about the name <code class="literal">BOOST_FOREACH</code>. It's
255      too long. <code class="computeroutput"><span class="identifier">ALL</span> <span class="identifier">CAPS</span></code>
256      can get tiresome to look at. That may be true, but <code class="literal">BOOST_FOREACH</code>
257      is merely following the <a href="http://www.boost.org/more/lib_guide.htm" target="_top">Boost
258      Naming Convention</a>. That doesn't mean you're stuck with it, though.
259      If you would like to use a different identifier (<code class="computeroutput"><span class="identifier">foreach_</span></code>,
260      perhaps), you can simply do:
261    </p>
262<pre class="programlisting"><span class="preprocessor">#define</span> <span class="identifier">foreach_</span>         <span class="identifier">BOOST_FOREACH</span>
263<span class="preprocessor">#define</span> <span class="identifier">foreach_r_</span>       <span class="identifier">BOOST_REVERSE_FOREACH</span>
264</pre>
265<p>
266      Only do this if you are sure that the identifier you choose will not cause
267      name conflicts in your code.
268    </p>
269<div class="note"><table border="0" summary="Note">
270<tr>
271<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="../../doc/src/images/note.png"></td>
272<th align="left">Note</th>
273</tr>
274<tr><td align="left" valign="top"><p>
275        Do not use <code class="computeroutput"><span class="preprocessor">#define</span> <span class="identifier">foreach_</span><span class="special">(</span><span class="identifier">x</span><span class="special">,</span><span class="identifier">y</span><span class="special">)</span> <span class="identifier">BOOST_FOREACH</span><span class="special">(</span><span class="identifier">x</span><span class="special">,</span><span class="identifier">y</span><span class="special">)</span></code>. This
276        can be problematic if the arguments are macros themselves. This would result
277        in an additional expansion of these macros. Instead, use the form shown above.
278      </p></td></tr>
279</table></div>
280<p>
281      Lastly, a word of warning. Lots of folks use a <code class="computeroutput"><span class="identifier">foreach</span></code>
282      macro as a short form for <code class="computeroutput"><span class="identifier">BOOST_FOREACH</span></code>.
283      I discourage this. It leads to name conflicts within the <code class="computeroutput"><span class="identifier">BOOST_FOREACH</span></code>
284      macro itself, where <code class="computeroutput"><span class="identifier">foreach</span></code>
285      is the name of a namespace. Besides, <code class="computeroutput"><span class="identifier">foreach</span></code>
286      is a common-enough identifier; even <a href="http://qt.digia.com/" target="_top">Qt</a>
287      defines it as a macro. If you insist on using <code class="computeroutput"><span class="identifier">foreach</span></code>,
288      you might try something like this:
289    </p>
290<pre class="programlisting"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">foreach</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span>
291
292<span class="keyword">namespace</span> <span class="identifier">boost</span>
293<span class="special">{</span>
294    <span class="comment">// Suggested work-around for https://svn.boost.org/trac/boost/ticket/6131</span>
295    <span class="keyword">namespace</span> <span class="identifier">BOOST_FOREACH</span> <span class="special">=</span> <span class="identifier">foreach</span><span class="special">;</span>
296<span class="special">}</span>
297
298<span class="preprocessor">#define</span> <span class="identifier">foreach</span>   <span class="identifier">BOOST_FOREACH</span>
299</pre>
300<p>
301      This will work around <span class="emphasis"><em>some</em></span> of the problems you're likely
302      to encounter, but not all. Prefer using a different identifier.
303    </p>
304</div>
305</div>
306<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
307<td align="left"><p><small>Last revised: August 11, 2020 at 15:03:46 GMT</small></p></td>
308<td align="right"><div class="copyright-footer"></div></td>
309</tr></table>
310<hr>
311<div class="spirit-nav">
312<a accesskey="p" href="boost_dll/acknowledgements.html"><img src="../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="libraries.html"><img src="../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="index.html"><img src="../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="foreach/extensibility.html"><img src="../../doc/src/images/next.png" alt="Next"></a>
313</div>
314</body>
315</html>
316