Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Have any of you tried Expected; in practice?</p> </blockquote> <p>It's quite natural, I used it even before I saw this talk.</p> <blockquote> <p>How would you apply this idiom to functions returning nothing (that is, void functions)?</p> </blockquote> <p>The form presented in the slides has some subtle implications:</p> <ul> <li>The exception is bound to the value.</li> <li>It's ok to handle the exception as you wish.</li> <li>If the value ignored for some reasons, the exception is suppressed.</li> </ul> <p>This does not hold if you have <code>expected&lt;void&gt;</code>, because since nobody is interested in the <code>void</code> value the exception is always ignored. I would force this as I would force reading from <code>expected&lt;T&gt;</code> in Alexandrescus class, with assertions and an explicit <code>suppress</code> member function. Rethrowing the exception from the destructor is not allowed for good reasons, so it has to be done with assertions.</p> <pre><code>template &lt;typename T&gt; struct expected; #ifdef NDEBUG // no asserts template &lt;&gt; class expected&lt;void&gt; { std::exception_ptr spam; public: template &lt;typename E&gt; expected(E const&amp; e) : spam(std::make_exception_ptr(e)) {} expected(expected&amp;&amp; o) : spam(std::move(o.spam)) {} expected() : spam() {} bool valid() const { return !spam; } void get() const { if (!valid()) std::rethrow_exception(spam); } void suppress() {} }; #else // with asserts, check if return value is checked // if all assertions do succeed, the other code is also correct // note: do NOT write "assert(expected.valid());" template &lt;&gt; class expected&lt;void&gt; { std::exception_ptr spam; mutable std::atomic_bool read; // threadsafe public: template &lt;typename E&gt; expected(E const&amp; e) : spam(std::make_exception_ptr(e)), read(false) {} expected(expected&amp;&amp; o) : spam(std::move(o.spam)), read(o.read.load()) {} expected() : spam(), read(false) {} bool valid() const { read=true; return !spam; } void get() const { if (!valid()) std::rethrow_exception(spam); } void suppress() { read=true; } ~expected() { assert(read); } }; #endif expected&lt;void&gt; calculate(int i) { if (!i) return std::invalid_argument("i must be non-null"); return {}; } int main() { calculate(0).suppress(); // suppressing must be explicit if (!calculate(1).valid()) return 1; calculate(5); // assert fails } </code></pre>
 

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