Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'd probably opt for returning an <code>optional</code>, since the streaming could fail. To test if it did (in case you want to assign another value), use <code>get_value_or(default)</code>, as shown in the example.</p> <pre><code>template&lt;class T, class Stream&gt; boost::optional&lt;T&gt; stream_get(Stream&amp; s){ T x; if(s &gt;&gt; x) return std::move(x); // automatic move doesn't happen since // return type is different from T return boost::none; } </code></pre> <p><a href="http://liveworkspace.org/code/0feaa0fac77c5ec1a3f3057f44b6769d">Live example.</a></p> <p>To further ensure that the user gets no wall-of-overloads presented when <code>T</code> is not input-streamable, you can write a trait class that checks if <code>stream &gt;&gt; T_lvalue</code> is valid and <code>static_assert</code> if it's not:</p> <pre><code>namespace detail{ template&lt;class T, class Stream&gt; struct is_input_streamable_test{ template&lt;class U&gt; static auto f(U* u, Stream* s = 0) -&gt; decltype((*s &gt;&gt; *u), int()); template&lt;class&gt; static void f(...); static constexpr bool value = !std::is_void&lt;decltype(f&lt;T&gt;(0))&gt;::value; }; template&lt;class T, class Stream&gt; struct is_input_streamable : std::integral_constant&lt;bool, is_input_streamable_test&lt;T, Stream&gt;::value&gt; { }; template&lt;class T, class Stream&gt; bool do_stream(T&amp; v, Stream&amp; s){ return s &gt;&gt; v; } } // detail:: template&lt;class T, class Stream&gt; boost::optional&lt;T&gt; stream_get(Stream&amp; s){ using iis = detail::is_input_streamable&lt;T, Stream&gt;; static_assert(iis::value, "T must support 'stream &gt;&gt; value_of_T'"); T x; if(detail::do_stream(x, s)) return std::move(x); // automatic move doesn't happen since // return type is different from T return boost::none; } </code></pre> <p><a href="http://liveworkspace.org/code/f1f8bcca190d3736e5d2d68e76d6e7f6">Live example.</a></p> <p>I'm using a <code>detail::do_stream</code> function, since otherwise <code>s &gt;&gt; x</code> would still be parsed inside <code>get_stream</code> and you'd still get the wall-of-overloads that we wanted to avoid when the <code>static_assert</code> fires. Delegating this operation to a different function makes this work.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload