Boost C++ Libraries: Ticket #10393: Add begin/end specialization for optional<T> type https://svn.boost.org/trac10/ticket/10393 <p> optional&lt;T&gt; could be used in many places as if it was just T, but, since C++ does not apply two levels of constructions one could not use this natural looking construct for optional containers: </p> <p> if (opt_container) { </p> <blockquote> <p> for (auto&amp; element : opt_container) { </p> <blockquote> <p> ... </p> </blockquote> <p> } </p> </blockquote> <p> } </p> <p> Simple specialization of begin()/end() functions could solve this problem: </p> <p> namespace std { </p> <p> template&lt;class T&gt; inline auto begin(const boost::optional&lt;T&gt;&amp; opt) -&gt; decltype(opt.get().begin()) { </p> <blockquote> <p> return opt.get().begin(); </p> </blockquote> <p> } </p> <p> template&lt;class T&gt; inline auto begin(boost::optional&lt;T&gt;&amp; opt) -&gt; decltype(opt.get().begin()) { </p> <blockquote> <p> return opt.get().begin(); </p> </blockquote> <p> } </p> <p> template&lt;class T&gt; inline auto end(const boost::optional&lt;T&gt;&amp; opt) -&gt; decltype(opt.get().end()) { </p> <blockquote> <p> return opt.get().end(); </p> </blockquote> <p> } </p> <p> template&lt;class T&gt; inline auto end(boost::optional&lt;T&gt;&amp; opt) -&gt; decltype(opt.get().end()) { </p> <blockquote> <p> return opt.get().end(); </p> </blockquote> <p> } </p> <p> } </p> en-us Boost C++ Libraries /htdocs/site/boost.png https://svn.boost.org/trac10/ticket/10393 Trac 1.4.3 rob.desbois@… Mon, 13 Apr 2015 17:00:38 GMT <link>https://svn.boost.org/trac10/ticket/10393#comment:1 </link> <guid isPermaLink="false">https://svn.boost.org/trac10/ticket/10393#comment:1</guid> <description> <p> You'd still have to check that the optional is initialized before doing so though. A simpler fix is to use the optional's dereference operator (when the optional&lt;T&gt; is initialized): </p> <div class="wiki-code"><div class="code"><pre> <span class="k">if</span> <span class="p">(</span><span class="n">opt_container</span><span class="p">)</span> <span class="k">for</span> <span class="p">(</span><span class="k">auto</span><span class="o">&amp;&amp;</span> <span class="nl">element</span> <span class="p">:</span> <span class="o">*</span><span class="n">opt_container</span><span class="p">)</span> <span class="p">{}</span> </pre></div></div><p> A really useful facility would be <code>begin()</code> &amp; <code>end()</code> overloads/specializations that could return an empty sequence when the optional is uninitialized, enabling direct passing of the <code>optional&lt;T&gt;</code> object to the range-for *without checking that it's initialized*. Given that in many cases (including standard library components) there's no way to construct a non-singular iterator without an underlying container this might be tricky...though a transparent wrapping iterator might do the trick. </p> </description> <category>Ticket</category> </item> </channel> </rss>