<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=US-ASCII">

<style type="text/css">
pre {margin-left:20pt; }
pre > i {
  font-family: "OCR A Extended", "Consolas", "Lucida Console", monospace;
  font-style:italic;
}
code > i {
  font-family: "OCR A Extended", "Consolas", "Lucida Console", monospace;
  font-style:italic;
}
pre > em {
  font-family: "OCR A Extended", "Consolas", "Lucida Console", monospace;
  font-style:italic;
}
code > em {
  font-family: "OCR A Extended", "Consolas", "Lucida Console", monospace;
  font-style:italic;
}
body { color: #000000; background-color: #FFFFFF; }
del { text-decoration: line-through; color: #8B0040; }
ins { text-decoration: underline; color: #005100; }

p.example { margin-left: 2em; }
pre.example { margin-left: 2em; }
div.example { margin-left: 2em; }

code.extract { background-color: #F5F6A2; }
pre.extract { margin-left: 2em; background-color: #F5F6A2;
  border: 1px solid #E1E28E; }

p.function { }
.attribute { margin-left: 2em; }
.attribute dt { float: left; font-style: italic;
  padding-right: 1ex; }
.attribute dd { margin-left: 0em; }

blockquote.std { color: #000000; background-color: #F1F1F1;
  border: 1px solid #D1D1D1;
  padding-left: 0.5em; padding-right: 0.5em; }
blockquote.stddel { text-decoration: line-through;
  color: #000000; background-color: #FFEBFF;
  border: 1px solid #ECD7EC;
  padding-left: 0.5empadding-right: 0.5em; ; }

blockquote.stdins { text-decoration: underline;
  color: #000000; background-color: #C8FFC8;
  border: 1px solid #B3EBB3; padding: 0.5em; }

table { border: 1px solid black; border-spacing: 0px;
  margin-left: auto; margin-right: auto; }
th { text-align: left; vertical-align: top;
  padding-left: 0.4em; border: none; 
  padding-right: 0.4em; border: none; }
td { text-align: left; vertical-align: top;
  padding-left: 0.4em; border: none;
  padding-right: 0.4em; border: none; }
</style>

<title>A proposal to add a utility class to represent optional objects (Revision 2)</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">$(function() {
    var next_id = 0
    function find_id(node) {
        // Look down the first children of 'node' until we find one
        // with an id. If we don't find one, give 'node' an id and
        // return that.
        var cur = node[0];
        while (cur) {
            if (cur.id) return curid;
            if (cur.tagName == 'A' && cur.name)
                return cur.name;
            cur = cur.firstChild;
        };
        // No id.
        node.attr('id', 'gensection-' + next_id++);
        return node.attr('id');
    };

    // Put a table of contents in the #toc nav.

    // This is a list of <ol> elements, where toc[N] is the list for
    // the current sequence of <h(N+2)> tags. When a header of an
    // existing level is encountered, all higher levels are popped,
    // and an <li> is appended to the level
    var toc = [$("<ol/>")];
    $(':header').not('h1').each(function() {
        var header = $(this);
        // For each <hN> tag, add a link to the toc at the appropriate
        // level.  When toc is one element too short, start a new list
        var levels = {H2: 0, H3: 1, H4: 2, H5: 3, H6: 4};
        var level = levels[this.tagName];
        if (typeof level == 'undefined') {
            throw 'Unexpected tag: ' + this.tagName;
        }
        // Truncate to the new level.
        toc.splice(level + 1, toc.length);
        if (toc.length < level) {
            // Omit TOC entries for skipped header levels.
            return;
        }
        if (toc.length == level) {
            // Add a <ol> to the previous level's last <li> and push
            // it into the array.
            var ol = $('<ol/>')
            toc[toc.length - 1].children().last().append(ol);
            toc.push(ol);
        }
        var header_text = header.text();
        toc[toc.length - 1].append(
            $('<li/>').append($('<a href="#' + find_id(header) + '"/>')
                              .text(header_text)));
    });
    $('#toc').append(toc[0]);
})
</script>
</head>

<body>


<!--<table>
<tr><td>Doc. no.</td><td>NXXXX=XX-XXXX</td></tr>
<tr><td>Date</td><td>YYYY-MM-DD</td></tr>
<tr><td valign='top'>Authors</td><td>Fernando Cacciola<br>Andrzej Krzemie&#x144;ski</td></tr>
<tr><td valign='top'>Contact</td><td><a href="mailto:fernando.cacciola@gmail.com">fernando.cacciola@gmail.com</a><br><a href='mailto:akrzemi1@gmail.com'>akrzemi1@gmail.com</a></td></tr>
<tr><td>Addresses</td><td>LWG</td></tr>
</table>-->

<h1><a name='title'>A proposal to add a utility class to represent optional objects (Revision&nbsp;2)</a></h1>

<p>
ISO/IEC JTC1 SC22 WG21 N3406 = 12-0096 - 2012-09-20
</p>

<address>
Fernando Cacciola, fernando.cacciola@gmail.com
</address>
<address>
Andrzej Krzemie&#x144;ski, akrzemi1@gmail.com

</address>


<h2><a name='intro'>Introduction</a></h2>

<p>Class template <code>optional&lt;T&gt;</code> proposed here is a <em>nullable</em> type <code>T</code> that can store in its storage space either a value of type <code>T</code> or a special value <code>nullopt</code>. Its interface allows to query whether a value of <code>T</code> or <code>nullopt</code> is currently stored.  The interface is based on Fernando Cacciola's
Boost.Optional library<sup>[2]</sup>, shipping since March, 2003, and widely used. It requires no changes to core language, and breaks no existing code. </p>

<h2><a name='toc'>Table of contents</a></h2>
<p id='toc'></p>

<h2><a name='revision'>Revision history</a></h2>

<p>Changes since <a href='http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1878.htm'>N1878=05-0138</a>:</p>
<ul>
  <li>Revised wording; the changes are now relative to <a href='http://www.open-std.org/jtc1/sc22/wg21/prot/14882fdis/n3290.pdf'>N3290</a>.</li>
  <li>Removed any form of assignment for optional references.</li>
  <li>Removed duplicate interface for accessing the value stored by the optional.</li>
  <li>Added in-place construction and assignment.</li>
  <li>Now using different tag <code>nullopt</code> instead of <code>nullptr</code> to indicate the 'disengaged' (uninitialized) optional.</li>
  <li>Included C++11 features: move semantics, <code>noexcept</code>, variadic templates, perfect forwarding, static initialization.</li>
  <li>Changed the motivation section.</li>
  <li>Changed the design rationale section.</li>
  <li>Added reference implementation</li>
</ul>




<h2><a name='motivation'>Motivation and scope</a></h2>



<h3><a name='motivation.missingval'>Missing return values</a></h3>


<p>It sometimes happens that a function that is declared to return values of type <code>T</code> may not have a value to return. For one instance, consider function <code>double sqrt(double)</code>. It is not defined for negative numbers. <em>The only way</em> function <b>sqrt</b> can find itself in the situation where it cannot produce a value is when it is passed an invalid argument, and it is possible for the caller to check if the argument is valid. Therefore, such cases are dealt with by stating a function <em>precondition</em>. Violating the precondition may either result in undefined behavior, or (as it is the case for <code>std::vector::at</code>) may be defined to throw an exception. However, there are cases where we cannot know whether a function is able to return a value before we call it. For instance: 

</p>

<pre>char c = stream.getNextChar();
int x = DB.execute("select x_coord from coordinates where point_id = 112209");
</pre>

<p>In the first case, one could argue that <code>stream</code> could provide another function for checking if the end of stream has been reached. But for the latter there is no easy way to make sure that the requested information exists in the database before we request for it. Also, throwing an exception is not a good solution, because there is nothing unusual or erroneous about not having found a record in the DB.
</p>



<h3><a name='motivation.optargs'>Optional function arguments</a></h3>


<p>Sometimes it is useful to indicate that we are unable or do not want to provide one of the function arguments:</p>

<pre>void execute( function&lt;void(int)&gt; fa, function&lt;void(int)&gt; fb )
{
  int i = computeI();
  fa(i); <em>// implicit assumption that fa != nullptr</em>
  if (fb) {
    fb(i);
  }
}
</pre>

<p>
Here, <code>fb</code> is an optional argument, and it typically requires an if-statement in function body. It is often argued that such design can be replaced by providing two function overloads, however this also is problematic: it adds certain duplication; may make the code less clear; the number of overloads increases expotentially with the number of optional parameters.
</p>



<h3><a name='motivation.trackinit'>Indicating a <em>null-state</em></a></h3>


<p>Some types are capable of storing a special <em>null-state</em> or <em>null-value</em>. It indicates that no 'meaningful' value has been assigned to the object yet. It is then possible to query the object whether it contains a null-state, typically by invoking a contextual conversion to type <code>bool</code> or by checking for equality with <code>nullptr</code>. Examples of such types include: <code>std::unique_ptr</code> or <code>std::function</code>. This is convenient for instance when implementing a <q>lazy initialization</q> optimization:

</p>

<pre>class Car 
{
  mutable unique_ptr&lt;const Engine&gt; engine_;
  
public:
  const Engine&amp; engine() const
  {
    if (engine_ == nullptr) {
      engine_.reset( new engine{engineParams()} );
    }
    return *engine_;
  }
};</pre>

<p>Other types, on the other hand, do not provide this capability. For instance, type <code>int</code> does not have a special value that would signal the null-state. Any value of <code>int</code> is a valid value. The same goes for user defined types: e.g., <code>Rational&lt;int&gt;</code> that implements a rational number by holding two <code>int</code>&rsquo;s representing a numerator and a denumerator.</p>

<p>For a similar example, consider this function for finding biggest <code>int</code>.</p>

<pre>
int find_biggest( const vector&lt;int&gt;& vec )
{
  int biggest; <em>// = what initial value??</em>
  for (int val : vec) {
    if (biggest &lt; val) {
      biggest = val;
    }
  }
  return biggest;
} 
</pre>

<p>
What initial value should we assign to <code>biggest</code>? Not 0, because the vector may hold negative values. We can use <code>std::numeric_limits&lt;int&gt;::min</code>. But what if we want to make our function generic? <code>std::numeric_limits</code> will not be specialized for any possible type. And what if the vector contains no elements? Shall we return minimum possible value? But how will the caller know if the size of the vector was zero, or if it was one with the minimum possible value?
</p>



<h3><a name='motivation.guards'>Manually controlling the lifetime of scope guards</a></h3>


<p>
Consider that you have to run three actions in the fixed order:
</p>
<pre>
void runAction1( Resource1 & );
void runAction2( Resource1 &, Resource2 & );
void runAction3( Resource2 & );
</pre>

<p>Of course, the two resources need to be acquired before using them and released once we are done. This is how we would write it conceptually, if we could assume that none of the operations ever fails or throws exceptions:</p>

<pre>
Result run3Actions( Parameter param ) <i>// BAD!!</i>
{
  Resource1 res1;
  Resource2 res2;

  res1.acquire(param);       <i>// res1 scope</i>
  runAction1( res1 );        <i>//</i>
  res2.acquire(param);       <i>//    // res2 scope</i>
  runAction2( res1, res2 );  <i>//    //</i>
  res1.release();            <i>//    //</i>
  runAction3( res2 );        <i>      //</i>
  res2.release();            <i>      //</i>
}
</pre>

<p>Note that the scopes of the two resources <em>overlap.</em> we cannot clearly divide our function into nested scopes that correspond to lifetimes of the resources. This example represents a real-life situation if you imagine that  <tt>runAction2</tt> is a critical operation, and <tt>runAction3</tt> (and perhaps <tt>runAction1</tt>) is logging, which we can even skip if it fails. </p>

<p>Of course, this code is unacceptable, because it does not take into account that  acquire operations, and the three actions may fail. So, we want to rewrite <tt>run3Actions</tt> using RAII idiom. Especially, that the library author that provides the interface to the two resources also knows that RAII is probably always what we want and the only interface he provides are scope guards: 

</p>

<pre>
Result run3Actions( Parameter param ) <i>// selfish</i>
{
  Resource1Guard res1{param};
  Resource2Guard res2{param};

  runAction1( res1 );
  runAction2( res1, res2 );   
  runAction3( res2 );
}
</pre>

<p>This solution is somewhat elegant: you first acquire all resources that you will need, and once you are sure you have them all, you just run the actions. But it has one problem. Someone else will also need to use resources we are acquiring. If they need it at the moment, but we own the resource right now, they will be locked, or thrown a refusal exception &mdash; they will be disturbed and delayed. Using a resource is a critical part of the program, and we should be only acquiring them for as short a period as possible, for the sake of efficiency: not only our program's but of the entire operating system. In our example above, we hold the ownership of <tt>res2</tt> while executing <tt>runAction1</tt>, which does not require the resource. Similarly, we unnecessarily hold <tt>res1</tt> when calling <tt>runAction3</tt>. </p>

<p>So, how about this?</p>

<pre>
Result run3Actions( Parameter param ) <i>// slow and risky</i>
{
  {
    Resource1Guard res1{param};
    runAction1( res1 );
  }
  {
    Resource1Guard res1{param};
    Resource2Guard res2{param};
    runAction2( res1, res2 );  
  }  
  {
    Resource2Guard res2{param};
    runAction3( res2 );
  } 
}
</pre>

<p>It does not have the above-mentioned problem, but it introduces a different one. Now we have to acquire the same resource two times in a row for two subsequent actions. Resource acquisition is critical, may lock us, may slow us down, may fail; calling it four times rather than two is wrong, especially that acquiring the same resource twice may give us different resource properties in each acquisition, and it may not work for our actions.</p> 

<h3><a name='motivation.skipinit'>Skipping the expensive initialization</a></h3>

<p>Not all types provide a cheap default construction, even if they are small in size. If we want to put such types in certain containers, we are risking paying the price of expensive default construction even if we want to assign a different value a second later.

</p>

<pre>ExpensiveCtor array[100]; <em>// 100 default constructions</em>
std::array&lt;ExpensiveCtor, 100&gt; arr; <em>// 100 default constructions</em>
std::vector&lt;ExpensiveCtor&gt; vec(100); <em>// 100 default constructions</em>

</pre>

<h3><a name='motivation.practise'>Current techniques for solving the problems</a></h3>


<p>The above mentioned problems are usually dealt with in C++ in three ways:</p>
<ol>
  <li>Using ad-hoc special values, like <code>EOF</code>, -1, 0, <code>numeric_limits&lt;T&gt;::min</code>.</li>

  <li>Using additional flags, like <code>pair&lt;T, bool&gt;</code>.</li>
  <li>Using pointers even if the object would have been passed or returned by value if it wouldn't be possibly absent.</li>
</ol>

<p>Technique (1) suffers from the lack of uniformity. Special value, like <code>EOF</code> is not something characteristic of the type (<code>int</code>), but of the particular function. Other function may need to use a different special value. The notable example is the standard function <code>atoi</code>, where 0 may indicate either an unsuccessful conversion, or a successful conversion to value 0. And again, sometimes it is not even possible to designate a value with a special meaning, because all values of a given type are equally likely to appear; for instance:

</p>

<pre>bool accepted = DB.execute("select accepted from invitations where invitation_id = 132208");</pre>

<p>Technique (2) is problematic because it requires both members of <code>pair</code> to be initialized. But one of the reasons we are not returning a 'normal' value from a function or do not want to initialize the object just yet, is because we did not know how to initialize it. In case of optional <code>int</code> we could give it a rubbish value or leave it uninitialized, but user defined types, including resources, may not provide a default constructor, and require some effort to perform initialization.</p>

<p>Technique (3) is general. It uses value <code>nullptr</code> to indicate the special value. Users can unequivocally test if the value is indeed absent and being formally undefined behavior to access an object pointed to by a null pointer. It also does not require initializing the object unnecessarily. But it comes with different problems. Automatic objects created inside functions cannot be returned by pointer. Thus it often requires creating objects in free store which may be more expensive than the expensive initialization itself. It also requires manual memory management problems. The latter problem can be dealt with by using <code>std::unique_ptr</code>, but this is still a pointer, and we must abandon value semantics. Now we return a smart pointer: we have shallow copy and shallow comparison.</p>



<h2><a name='overview'>Overview of <code>optional</code></a></h2>


<p>The utility presented here is not a smart pointer. Even though it provides operators <code>-></code> and <code>*</code>, it has full value semantics: deep copy construction, deep copy assignmet, deep equality and less-than comparison, and constness propagation (from optional object to the contained value).</p>

<p>Conceptually, <code>optional</code> can be illustrated by the following structure.</p>

<pre>template &lt;typename T&gt;
struct optional
{
  bool is_initialized_;
  typename aligned_storage&lt;sizeof(T), alignof(T)&gt;::type storage_;
};</pre>

<p>Flag <code>is_initialized_</code> stores the information if <code>optional</code> has been assigned a value of type <code>T</code>. <code>storage_</code> is a raw fragment of memory (allocated within <code>optional</code> object) capable of storing an object of type <code>T</code>. Objects in this storage are created and destroyed using placement <code>new</code> and pseudo destructor call as member functions of <code>optional</code> are executed and based on the value of flag <code>is_initialized_</code>.</p> 

<p>Alternatively, one can think of <code>optional&lt;T&gt;</code> as <code>pair&lt;bool, T&gt;</code> with one important difference: if <code>first</code> is <code>false</code>, member <code>second</code> has never been even initialized, even with default constructor or value-initialization.</p>


<p>Default construction of <code>optional&lt;T&gt;</code> creates an an object that stores no value of type <code>T</code>. No default constructor of <code>T</code> is called. <code>T</code> doesn't even need to be <code>DefaultConstructible</code>. We say that thus created optional object is <em>disengaged</em>. We need the pair of artificial names, 'engaged' and 'disengaged', in order not to overload the regular meaning of terms 'initialized' and 'uninitialized'. The optional object is initialized (the lifetime of <code>optional&lt;T&gt;</code> has started), but it is disengaged (the lifetime of the contained object has not yet started). Trying to access the value of <code>T</code> in this state causes undefined behavior. The only thing we can do with a disengaged optional object is to query whether it is engaged, copy it, compare it with another <code>optional&lt;T&gt;</code>, or <em>engage</em> it.</p>

<pre>optional&lt;int&gt; oi;                 <em>// create disengaged object</em>
optional&lt;int&gt; oj = nullopt;       <em>// alternative syntax</em>
oi = oj;                          <em>// assign disengaged object</em>
optional&lt;int&gt; ok = oj;            <em>// ok is disengaged</em>

if (oi)  assert(false);           <em>// 'if oi is engaged...'</em>
if (!oi) assert(true);            <em>// 'if oi is disengaged...'</em>

if (oi != nullopt) assert(false); <em>// 'if oi is engaged...'</em>
if (oi == nullopt) assert(true);  <em>// 'if oi is disengaged...'</em>

assert(oi == ok);                 <em>// two disengaged optionals compare equal</em>

</pre>

<p>We can create engaged optional objects or engage existing optional objects by using converting constructor (from type <code>T</code>) or by assigning a value of type <code>T</code>.

<pre>optional&lt;int&gt; ol{1};              <em>// ol is engaged; its contained value is 1</em>
ok = 2;                           <em>// ok becomes engaged; its contained value is 2</em>
oj = ol;                          <em>// oj becomes engaged; its contained value is 1</em>

assert(oi != ol);                 <em>// disengaged != engaged</em>
assert(ok != ol);                 <em>// different contained values</em>
assert(oj == ol);                 <em>// same contained value</em>
assert(oi &lt; ol);                  <em>// disengaged &lt; engaged</em>
assert(ol &lt; ok);                  <em>// less by contained value</em>
</pre>

<p>We access the contained value using the indirection operator.</p>

<pre>int i = *ol;                      <em>// i obtains the value contained in ol</em>
assert(i == 1);
*ol = 9;                          <em>// the object contained in ol becomes 9</em>
assert(*ol == 9);

</pre>

<p>We also provide consistent <code>operator-&gt;</code>. The typical usage of <code>optional</code> requires an if-statement.</p>

<pre>if (ol)                      
  process(*ol);                   <em>// use contained value if present</em>
else
  processNil();                   <em>// proceed without contained value</em>
</pre>

 
<p>If the action to be taken for disengaged <code>optional</code> is to proceed with the default value, we provide a convenient idiom: </p> 

<pre>process(get_value_or(ol, 0));     <em>// use 0 if ol is disengaged</em>
</pre>

<p>Sometimes the initialization from <code>T</code> may not do. If we want to skip the copy/move construction for <code>T</code> because it is too expensive or simply not available, we can call an 'emplacing' constructor, or function <code>emplace</code>.</p>

<pre>optional&lt;Guard&gt; oga;                     <em>// Guard is non-copyable (and non-moveable)</em>     
optional&lt;Guard&gt; ogb(emplace, "res1");    <em>// initialzes the contained value with "res1" </em>           
optional&lt;Guard&gt; ogc(emplace);            <em>// default-constructs the contained value</em>

oga.emplace("res1");                     <em>// initialzes the contained value with "res1" </em> 
oga.emplace();                           <em>// destroys the contained value and </em>
                                         <em>// default-constructs the new one</em>
</pre>

<p>There are two ways to <em>disengage</em> a perhaps engaged optional object:</p>

<pre>ok = nullopt;                      <em>// if ok was engaged calls T's dtor</em>
oj = {};                           <em>// assigns a temporary disengaged optional</em>
oga = nullopt;                     <em>// OK: disengage the optional Guard</em>
ogb = {};                          <em>// ERROR: Guard is not Moveable</em>
</pre>


<p>Optional propagates constness to its contained value:</p>

<pre>const optional&lt;int&gt; c = 4; 
int i = *c;                        <em>// i becomes 4</em>
*c = i;                            <em>// ERROR: cannot assign to const int&amp;</em>
</pre>


<p>It is also possible to create optional lvalue references, although their interface is limited.</p>

<pre>int i = 1;
int j = 2;
optional&lt;int&amp;&gt; ora;                 <em>// disengaged optional reference to int</em>
optional&lt;int&amp;&gt; orb = i;             <em>// contained reference refers to object i</em>

*orb = 3;                          <em>// i becomes 3</em>
ora = j;                           <em>// ERROR: optional refs do not have assignment from T</em>
ora = {j};                         <em>// ERROR: optional refs do not have copy/move assignment</em>
ora = orb;                         <em>// ERROR: no copy/move assignment</em>
ora.emplace(j);                    <em>// OK: contained reference refers to object j</em>
ora.emplace(i);                    <em>// OK: contained reference now refers to object i</em>

ora = nullopt;                     <em>// OK: ora becomes disengaged</em>
</pre>

<p>Since optional lvalue references are rebindable, may be disengaged, and do not have special powers (such as extending the life-time of a temporary), they are very similar to pointers, except that they do not provide pointer arithmetic. Optional rvalue references are not allowed.
</p>


<h3><a name='overview.except.safety'>Exception safety</a></h3>


<p>Type <code>optional&lt;T&gt;</code> is a wrapper over <code>T</code>, thus its exception safety guarantees depend on exception safety guarantees of <code>T</code>. We expect (as is the case for the entire C++ Standard Library) that destructor of <code>T</code> does not throw exceptions. Copy assignment of <code>optional&lt;T&gt;</code> provides the same exception guarantee as copy assignment of <code>T</code> and copy constructor of <code>T</code> (i.e., the weakest of the two). Move assignment of <code>optional&lt;T&gt;</code> provides the same exception guarantee as move assignment of <code>T</code> and move constructor of <code>T</code>. Member function <code>emplace</code> provides basic guarantee: if exception is thrown, <code>optional&lt;T&gt;</code> becomes disengaged, regardless of its prior state. No operation on optional references throws exceptions. </p>



<h3><a name='overview.usecases'>Advanced use cases</a></h3>


<p>With <code>optional&lt;T&gt;</code> problems described in Motivation section can be solved as follows. For lazy initialization:</p>


<pre>class Car 
{
  mutable optional&lt;const Engine&gt; engine_;
  mutable optional&lt;const int&gt; mileage_
  
public:
  const Engine&amp; engine() const
  {
    if (engine_ == nullopt) engine_.emplace( engineParams() );
    return *engine_;
  }
  
  const int&amp; mileage() const
  {
    if (!mileage_) mileage_ = initMileage();
    return *mileage_;
  }
};</pre>

<p>The algorithm for finding the greatest element in vector can be written as: </p>


<pre>
optional&lt;int&gt; find_biggest( const vector&lt;int&gt;& vec )
{
  optional&lt;int&gt; biggest;  <em>// initialized to not-an-int</em>
  for (int val : vec) {
    if (!biggest || *biggest &lt; val) {
      biggest = val;
      <em>// or: biggest.emplace(val);</em>
    }
  }
  return biggest;
} 
</pre>

<p>Or, if the caller may wish to modify the smallest element:</p>

<pre>
optional&lt;int&amp;&gt; find_biggest( vector&lt;int&gt;& vec )
{
  optional&lt;int&amp;&gt; biggest; 
  for (int & val : vec) {
    if (!biggest || *biggest &lt; val) {
      biggest.emplace(val);
    }
  }
  return biggest;
} 

</pre>

<p>Missing return values are naturally modelled by optional values:</p>

<pre>optional&lt;char&gt; c = stream.getNextChar();
optional&lt;int&gt; x = DB.execute("select ...");

storeChar( get_value_or(c, '\0') );
storeCount( get_value_or(x, -1) );
</pre>

<p>Optional arguments can be implemented as follows:<p>

<pre>template &lt;typename T&gt;
T getValue( optional&lt;T&gt; newVal = nullopt, optional&lt;T&amp;&gt; storeHere = nullopt )
{
  if (newVal) {
    cached = *newVal;
    
    if (storeHere) {
      *storeHere = *newVal; <em>// LEGAL: assigning T to T</em>
    }      
  }
  return cached;      
}
</pre>

<p>Manually controlling the life-time of guard-like objects can be achieved by emplacement operations and <code>nullopt</code> assignment:</p>

<pre>{
  optional&lt;Guard&gt; grd1{emplace, "res1", 1};   <em>// guard 1 initialized</em>
  optional&lt;Guard&gt; grd2;

  grd2.emplace("res2", 2);                     <em>// guard 2 initialized</em>
  grd1 = nullopt;                              <em>// guard 1 released</em>

}                                              <em>// guard 2 released (in dtor)</em>
</pre>

<p>It is possible to use <code>tuple</code> and <code>optional</code> to emulate multiple return valuse for types without default constructor:</p>

<pre>tuple&lt;Date, Date, Date&gt; getStartMidEnd();
void run(Date const&amp;, Date const&amp;, Date const&amp;);
<em>// ...</em>

optional&lt;Date&gt; start, mid, end;           <em>// Date doesn't have default ctor (no good default date)</em>

tie(start, mid, end) = getStartMidEnd();
run(*start, *mid, *end); 
</pre>



<h3><a name='overview.value_ptr_compartson'>Comparison with <code>value_ptr</code></a></h3>

<p><a href='http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3339.pdf'>N3339</a><sup>[7]</sup> proposes a smart pointer template <code>value_ptr</code>. In short, it is a smart pointer with deep copy semantics. It has a couple of features in common with <code>optional</code>: both contain the notion of optionality, both are deep-copyable. Below we list the most important differences. </p>

<p><code>value_ptr</code> requires that the pointed-to object is allocated in the free store. This means that the <code>sizeof(value_ptr&lt;T&gt;)</code> is fixed irrespective of <code>T</code>. <code>value_ptr</code> is 'polymorphic': object of type <code>value_ptr&lt;T&gt;</code> can point to an object of type <code>DT</code>, derived from <code>T</code>. The deep copy preserves the dynamic type. <code>optional</code> requires no free store allocation: its creation is more efficient; it is not "polymorphic".</p>

<p>Relational operations on <code>value_ptr</code> are shallow: only addresses are compared. Relational operations on <code>optional</code> are deep, based on object's value. In general, <code>optional</code> has a well defined value: being disengaged and the value of contained value (if it exists); this value is expressed in the semantics of equality operator. This makes <code>optional</code> a full value-semantic type. Comparison of <code>value_ptr</code> does not have this property: copy semantics are incompatible with equality comparison semantics: a copy-constructed <code>value_ptr</code> does not compare equal to the original. <code>value_ptr</code> is not a value semantic type. 
</p>


<h2><a name='rationale'>Design rationale</a></h2>


<p>Nearly every function in the interface of <code>optional</code> has risen some controversies. Different people have different expectations and different concerns and it is not possible to satisfy all conflicting requirements. Yet, we believe that <code>optional</code> is so universally useful, that it is worth standardizing it even at the expense of introducing a contorversial interface. The current proposal reflects our arbitrary choice of balance between unambiguousity, genericity and flexibility of the interface. The interface is based on Fernanndo Cacciola's <a href='http://www.boost.org/doc/libs/1_48_0/libs/optional/doc/html/index.html'>Boost.Optional</a> library,<sup>[2]</sup> and the users' feedback. The library has been widely accepted, used and even occasionally recommended ever since. 
</p>



<h3><a name='rationale.model'>Conceptual model for <code>optional&lt;T&gt;</code></a></h3>


<p>Optional objects serve a number of purposes and a couple of conceptual models can be provided to answer the question what <code>optional&lt;T&gt;</code> really is and what interface it should provide. The three most common models are:</p>

<ol>
  <li>Just a <code>T</code> with deferred initialization (and additional interface to check if the object has already been initialized).</li>
  <li>A discriminated union of types <code>nullopt_t</code> and <code>T</code>.</li>
  <li>A container of <code>T</code>'s with the maximum size of 1.</li>
</ol>

<p>While (1) was the first motivation for <code>optional</code>, we do not choose to apply this model, because type <code>optional&lt;T&gt;</code> would not be a value semantic type: it would not model concept <code>Regular</code> (if C++ had concepts). In particular, it would be not clear whather being engaged or disengaged is part of the object's state. Programmers who wish to adapt this view, and don't mind the mentioned difficulties, can still use <code>optional</code> this way:</p>

<pre>optional&lt;int&gt; oi;
initializeSomehow(oi);

int i = (*oi);
use(*oi);
(*oi) = 2;
cout &lt;&lt; (*oi);
</pre>

<p>Note that this usage does not even require to check for engaged state, if one is sure it has been performed. One just needs to use indirection operator consistently anywhere one means to use the initialized value. </p>

<p>Model (2) treats <code>optional&lt;T&gt;</code> as etier a value of type <code>T</code> or value <code>nullopt</code>, allocated in the same storage, along with the way of determining which of the two it is. The interface in this model requires operations such as comparison to <code>T</code>, comparison to <code>nullopt</code>, assignment and creation from either. It is easy to determine what the value of the optional object is in this model: the type it stores (<code>T</code> or <code>nullopt_t</code>) and possibly the value of <code>T</code>. This is the model that we propose.</p>

<p>Model (3) treats <code>optional&lt;T&gt;</code> as a special case container. This begs for a container-like interface: <code>empty</code> to check if the object is disengaged, <code>emplace</code> to engage the object, and <code>clear</code> to disengage it. Also, the value of optional object in this model is well defined: the size of the container (0 or 1) and the value of the element if the size is 1. This model would serve our pupose equally well. The choice between models (2) and (3) is to a certain degree arbitrary. One argument in favour of (2) is that it has been used in practise for a while in Boost.Optional.</p>



<h3><a name='rationale.initialization_variants'>Initialization of <code>optional&lt;T&gt;</code></a></h3>


<p>In cases <code>T</code> is a value semantic type capable of storing <em>n</em> distinct values, <code>optional&lt;T&gt;</code> can be seen as an extended <code>T</code> capable of storing <em>n</em> + 1 values: these that <code>T</code> stores and <code>nullopt</code>. Any valid initialization scheme must provide a way to put an optional objects to any of these states. In addition, some <code>T</code>s (like scope guards) are not <code>MoveConstructible</code> and their optional variants still should constructible with any set of arguments that work for <code>T</code>. Two models have been identified as feasible.</p>

<p>The first requires that you initialize either by providing an already constructed <code>T</code> on the tag <code>nullopt</code>.</p>

<pre>string s{"STR"};

optional&lt;string&gt; os{s};                   <em> // requires Copyable&lt;T&gt;</em>
optional&lt;string&gt; ot = s;                  <em> // requires Copyable&lt;T&gt;</em>
optional&lt;string&gt; ou{"STR"};               <em> // requires Movable&lt;T&gt;</em>
optional&lt;string&gt; ov = string{"STR"};      <em> // requires Movable&lt;T&gt;</em>

optional&lt;string&gt; ow;                      <em> // disengaged</em>
optional&lt;string&gt; ox{};                    <em> // disengaged</em>
optional&lt;string&gt; oy = {};                 <em> // disengaged</em>
optional&lt;string&gt; oz = optional&lt;string&gt;{}; <em> // disengaged</em>
optional&lt;string&gt; op{nullopt};             <em> // disengaged</em>
optional&lt;string&gt; oq = {nullopt};          <em> // disengaged</em>
</pre>

<p>In order to avoid calling move/copy constructor of <code>T</code>, we use a 'tagged' placement constructor: </p>

<pre>optional&lt;Guard&gt; og;                       <em> // disengaged</em>
optional&lt;Guard&gt; oh{};                     <em> // disengaged</em>
optional&lt;Guard&gt; oi{emplace};              <em> // calls Guard{} in place</em>
optional&lt;Guard&gt; oj{emplace, "arg"};       <em> // calls Guard{"arg"} in place</em>
</pre>

<p>The in-place constructor is not strictly necessary. It could be dropped because one can always achieve the same effect with a two-liner:</p>

<pre>optional&lt;Guard&gt; oj;                       <em> // start disengaged</em>
oj.emplace("arg");                        <em> // now engage</em>
</pre>


<p>Notably, there are two ways to create a disengaged optional object: either by using the default constructor or by calling the 'tagged constructor' that takes <code>nullopt</code>. One of these could be safely removed and <code>optional&lt;T&gt;</code> could still be initialized to any state. </p>

<p>An alternative and also comprehensive initialization scheme is to have a variadic perfect forwarding constructor that just forwards any set of arguments to the constructor of the contained object of type <code>T</code>:

<pre><em>// not proposed</em>

optional&lt;string&gt; os{"STR"};               <em> // calls string{"STR"} in place </em>
optional&lt;string&gt; ot{2, 'a'};              <em> // calls string{2, 'a'} in place</em>
optional&lt;string&gt; ou{};                    <em> // calls string{} in place</em>
optional&lt;string&gt; or;                      <em> // calls string{} in place</em>

optional&lt;Guard&gt; og;                       <em> // calls Guard{} in place</em>
optional&lt;Guard&gt; oh{};                     <em> // calls Guard{} in place</em>
optional&lt;Guard&gt; ok{"arg"};                <em> // calls Guard{"arg"} in place</em>

optional&lt;vector&lt;int&gt;&gt; ov;                 <em> // creates 0-element vector</em>
optional&lt;vector&lt;int&gt;&gt; ow{};               <em> // creates 0-element vector</em>
optional&lt;vector&lt;int&gt;&gt; ox{5, 6};           <em> // creates 5-element vector</em>
optional&lt;vector&lt;int&gt;&gt; oy{{5, 6}};         <em> // creates 2-element vector</em>
</pre>

<p>In order to create a disengaged optional object a special tag needs to be used: either <code>nullopt</code> or <code>T</code>-based:</p>

<pre>optional&lt;int&gt; oi = nullopt;               <em> // disengaged </em>
optional&lt;int&gt; oj = optional&lt;int&gt;::nullopt;<em> // disengaged</em>
</pre>

<p>The latter, perfect forwarding variant, has an obvious advantage: whatever you can initialize <code>T</code> with, you can also use it to initialize <code>optional&lt;T&gt;</code> with the same semantics. It becomes even ore useful in copy-initialization contextx like returning values from functions or passing arguments to functions:</p>

<pre>void putch(optional&lt;char&gt; oc);
putch('c');
putch({});       // char '\0'
putch(nullopt);  // no char
</pre>

<p> However, there are also certain problems with this model. First, there are exceptions to perfect forwarding: the tag <code>nullopt</code> is not forwarded. Also, arguments of type <code>optional&lt;T&gt;</code> are not. This becomes visible if <code>T</code> has such constructor:</p>

<pre>struct MyType
{
  MyType(optional&lt;MyType&gt;, int = 0);
  <em>// ... </em>
};
</pre>

<p>Also, in general, it is impossible to perfect-forward <code>initializer_list</code> as the special deduction rules are involved. Second problem is that <code>optional</code>'s default constructor creates an engaged object and therby triggers the value-initialization of <code>T</code>. It can be argued that this is only a psychological argument resulting from the fact that other <code>std</code> components behave this way: containers, smart pointers, <code>function</code>, and only because perfect forwarding was not available at the time they were designed. However we anticipate that this expectation (valid or not) could cause bugs in programs. Consider the following example:</p>

<pre>optional&lt;char&gt; readChar(Stream str)
{
  optional&lt;char&gt; ans;

  if (str.buffered()) {
    ans = str.readBuffered();
    clearBuffer();
  }
  else if (!str.end()) {
    ans = str.readChar();
  }

  return ans;
} 
</pre>

<p>This is so natural to expect that <code>ans</code> is not engaged until we decide how we wan to engage it, that people will write this code. And in the effect, if they cannod read the character, they will return an engaged optional object with value <code>'\0'</code>. For these reasons we choose to propose the former model.</p>



<h3><a name='rationale.default_ctor'>The default constructor</a></h3>


<p>This proposal provides a default constructor for <code>optional&lt;T&gt;</code> that creates a disengaged optional. We find this feature convenient for a couple of reasons. First, it is because this behaviour is intuitive as shown in the above example of function <code>readChar</code>. It avoids a certain kind of bugs. Also it satisfies other expectations. If I declare <code>optional&lt;T&gt;</code>  as a non-static member, without any initializer, I may expect it is already initialized to the most natural, disengaged, state regardless of whether <code>T</code> is <code>DefaultConstructible</code> or not. Also when declaring a global object, one could expect that default constructor would be initialized during static-initialization (this proposal guarantees that). One could argue that the tagged constructor could be used for that puropse: </p>

<pre>
int global = nullopt;

struct X
{
  optional&lt;M&gt; m = nullopt;
};
</pre>

<p>However, sometimes not providing the tag may be the result of an inadvertent omission rather than concious decision. Because of our default constructor semantics we have to reject the initialization scheme that yses a perfect forwarding constructor. Even if this is fine, one could argue that we do not need a default constructor if we have a tagged constructor. We find this redundancy convenient. For instance, how do you resize a <code>vector&lt;optional&lt;T&gt;&gt;</code> if you do not have the default constructor? You could type:</p>

<pre>vec.resize(size, nullopt);</pre>

<p>However, that causes first the creation od disengaged optional, and then copying it multiple times. The use of copy constructor may incur run-time overhead and not be available for non-copyable <code>T</code>s. Also, it would be not possible to use subscript operator in maps that hold opitonal objects.</p>

<p>Also, owing to this constructor, <code>optional</code> has a nice side-effect feature: it can make "almost <code>Regular</code>" types fully <code>Regular</code> if the lack od default constructor is the only thing they are missing. For instance consider type <code>Date</code> for representing calendar days: it is copyable movable, comparable, but is not <code>DefaultConstructible</code> because there is no meaningful default date. However, <code>optional&lt;Date&gt;</code> is <code>Regular</code> with a meaningful not-a-date state created by default.</p>



<h3><a name='rationale.converting_ctor'>Converting constructor (from <code>T</code>)</a></h3>


<p>An object of type <code>T</code> is convertible to an engaged opbject of type <code>optional&lt;T&gt;</code>:</p>

<pre>optional&lt;int&gt; oi = 1; <em>// works</em></pre>

<p>This convenience feature is not strictly necessary because you can achieve the same effect by using tagged forwarding constructor:</p>

<pre>optional&lt;int&gt; oi{emplace, 1};</pre>

<p>If the latter appears too inconvenient, one can always use funciotn <code>make_optional</code> described below:</p>
 
<pre>optional&lt;int&gt; oi = make_optional(1); 
auto oj = make_optional(1); 
</pre>

<p>If the above still appears inconvenient, one could argue that <code>optional</code>'s constructor from <code>T</code> could still be provided but made explicit. We decided to enable implicit conversion, because it is in accord with the view of optional as an extended type <code>T</code> capable of storing all 'normal' values of <code>T</code> + one additional value: <code>nullopt</code> this is reflected in object construction and assignment:</p>

<pre>optional&lt;unsigned&gt; oi = 1;
optional&lt;unsigned&gt; oj = 0;
optional&lt;unsigned&gt; ok = nullopt;

oi = nullopt;
oj = 0;
ok = 1;
</pre>

<p>For the same reason, also construction from <code>nullopt</code> is non-explicit. Although, in this picture name 'none' for the tag (rather than 'nullopt') would better serve the purpose. In contrast, accessor functions (including comparison operators) do not expose such symmetric interface. Such implicit conversions impose some risk of introducing bugs, and in fact in order to avoid one such possible bug we had to 'poison' comparisons between <code>optional&lt;T&gt;</code> and <code>T</code>. (This is explained in detail in section on relational operators.)</p>


<h3><a name='rationale.bool_conversion'>Contextual conversion to <code>bool</code> for checking engaged state</a></h3>


<p>Objections have been risen to this decision. When using <code>optional&lt;bool&gt;</code>, contextual conversion to <code>bool</code> (used for checking the engaged state) might be confused with accessing the stored value. while such mistake is possible, it is not precedent in the standard: types <code>bool*</code>, <code>unique_ptr&lt;bool&gt;</code>, <code>shared_ptr&lt;bool&gt;</code> suffer from the same potential problem, and it was never considered a show-stopper. Some have suggested that a special case in the interface should be made for <code>optional&lt;bool&gt;</code> specialization. This was however rejected because it would break the generic use of <code>optional</code>. </p>

<p>Some have also suggested that a member function like <code>is_initialized</code> would more clearly indicate the intent than explicit conversion to <code>bool</code>. However, we believe that the latter is a well established idiom in C++ comunity as well as in the C++ Standard Library, and <code>optional</code> appears so fundamental a type that a short and familiar notation appears more appropriate. It also allows us to combine the construction and checking for being engaged in a condition:
	</p>

<pre>if (optional&lt;char&gt; ch = readNextChar()) {
  // ...
}
</pre>


<h3><a name='rationale.nullopt'>Using tag <code>nullopt</code> for indicating disengaged state</a></h3>

<p>The proposed interface uses special tag <code>nullopt</code> to indicate disengaged <code>optional</code> state. It is used for construction, assignment and relational operations. This might rise a couple of objections. First, it introduces redundancy into the interface:</p>

<pre>optional&lt;int&gt; opt1 = nullopt; 
optional&lt;int&gt; opt2 = {}; 

opt1 = nullopt;
opt2 = {};

if (opt1 == nullopt) ...
if (!opt2) ...
if (opt2 == optional&lt;int&gt;{}) ...
</pre>

<p>On the other hand, there are usages where the usage of <code>nullopt</code> cannot be replaced with any other convenient notation:</p>

<pre>void run(complex&lt;double&gt; v);
void run(optional&lt;string&gt; v);

run(nullopt);            <em>// pick the second overload</em>
run({});                 <em>// ambiguous</em>

if (opt1 == nullopt) ... <em>// fine</em>
if (opt2 == {}) ...      <em>// ilegal</em>
</pre>

<p>While some situations would work with <code>{}</code> syntax, using <code>nullopt</code> makes the programmer's intention more clear. Compare these:</p>

<pre>optional&lt;vector&lt;int&gt;&gt; get1() {
  return {};
}

optional&lt;vector&lt;int&gt;&gt; get2() {
  return nullopt;
}

optional&lt;vector&lt;int&gt;&gt; get3() {
  return optional&lt;vector&lt;int&gt;&gt;{};
}
</pre>

<p>The usage of <code>nullopt</code> is also a consequence of the adapted model for optional: a discriminated union of <code>T</code> and <code>nullopt_t</code>. Also, a similar redundancy in the interface already exists in a number of components in the standard library: <code>unique_ptr</code>, <code>shared_ptr</code>, <code>function</code> (which use literal <code>nullptr</code> for the same purpose); in fact, type requirements <code>NullablePointer</code> require of types this redundancy. </p>

<p>Name "nullopt" has been chosen because it clearly indicates that we are interested in creating a null (disengaged) <code>optional&lt;T&gt;</code> (of unspecified type <code>T</code>). Other short names like "null", "naught", "nothing" or "none" (used in Boost.Optional library) were rejected because they were too generic: they did not indicate unambiguously that it was <code>optional&lt;T&gt;</code> that we intend to create. Such a generic tag <code>nothing</code> could be useful in many places (e.g., in types like <code>variant&lt;nothing_t, T, U&gt;</code>), but is outside the scope of this proposal.</p>
 

<p>Note also that the definition of tag struct <code>nullopt</code> is more complicated than that of other, similar, tags: it has explicitly deleted default constructor. This is in order to enable the reset idiom (<code>opt2 = {};</code>), which would otherwise not work because of ambiguuity when deducing the right-hand side argument.</p>


<h3><a name='rationale.no_nullptr'>Why not <code>nullptr</code></a></h3>


<p>One could argue that since we have keyword <code>nullptr</code>, which already indicates a 'null-state' for a number of Standard Library types, not necessarily pointers (class template <code>function</code>), it could be equally well used for <code>optional</code>. In fact, the previous revision of this proposal did propose <code>nullptr</code>, however there are certain difficulties that arise when the null-pointer literal is used.</p>

<p>First, the interface of <code>optional</code> is already criticized for resembling too much the interface of a (raw or smart) pointer, which incorrectly suggests external heap storage and shallow copy and comparison semantics. The "ptr" in "nullptr" would only increase this confusion. While <code>std::function</code> is not a pointer either, it also does not provide a confusing <code>operator-&gt;</code>, or equality comparison, and in case it stores a function pointer it does shallow copying.</p>

<p>Second, using literal <code>nullptr</code> in <code>optional</code> would make it impossible to provide some of the natural and expected initialization and assignment semantics for types that themselves are nullable:</p>

<ul>
<li><code>optional&lt;int*&gt;</code>, </li>
<li><code>optional&lt;const char*&gt;</code>, </li>
<li><code>optional&lt;M C::*&gt;</code>, </li>
<li><code>optional&lt;function&lt;void(int)&gt;&gt;</code>, </li>
<li><code>optional&lt;NullableInteger&gt;</code>,</li>
<li><code>optional&lt;nullptr_t&gt;</code>.</li>
</ul>

<p>Should the following initialization render an engaged or a disengaged optional?</p>

<pre>optional&lt;int*&gt; op = nullptr;</pre>

<p>One could argue that if we want to initialize an engaged optional we should indicate that explicitly: </p>

<pre>optional&lt;int*&gt; op{emplace, nullptr};</pre>

<p>But this argument would not work in general. One of the goals of the design of <code>optional</code> is to allow a seamless "optionalization" of function arguments. That is, given the folowing function signature:</p>

<pre>void fun(T v) {
  process(v);
}
</pre>

<p>It should be possible to change the signature and the implementation to:</p>

<pre>void fun(optional&lt;T&gt; v) {
  if (v) process(*v);
  else   doSthElse();
}
</pre>

<p>and expect that all the places that call function <code>fun</code> are not affected. But if <code>T</code> happens to be <code>int*</code> and we occasionally pass value <code>nullptr</code> to it, we will silently change the intended behavior of the refactoring: because it will not be the pointer that we null-initialize anymore but a disengaged optional.</p>

<p>Note that this still does not save us from the above problem with refactoring function <code>fun</code> in case where <code>T</code> happens to be <code>optional&lt;U&gt;</code>, but we definately limit the amount of surprises.</p>

<p>In order to avoid similar problems with tag <code>nullopt</code>, instantiating template <code>optional</code> with types <code>nullopt_t</code> and <code>emplace_t</code> is prohibitted.</p>

<p>There exist, on the other hand, downsides of introducing a special token in place of <code>nullptr</code>. The number of ways to indicate the 'null-state' for different library components will grow: you will have <code>NULL</code>, <code>nullptr</code>, <code>nullopt</code>. New C++ programmers will ask "which of these should I use now?" What guidelines should be provided? Use only <code>nullptr</code> for pointers? But does it mean that we should use <code>nullopt</code> for <code>std::function</code>? Having only one way of denoting null-state, would make the things easier, even if "ptr" suggests a pointer. </p>


<h3><a name='rationale.t_based_none'>Why not a tag dependent on <code>T</code>? </a></h3>


<p>It has been suggested that instead of 'typeless' <code>nullopt</code> a tag nested in class <code>optional</code> be used instead:</p>

<pre>optional&lt;int&gt; oi = optional&lt;int&gt;::nullopt;
</pre>

<p>This has several advanages. Namespace <code>std</code> is not polluted with an additional <code>optional</code>-specific name. Also, it resolves certain ambiguities when types like <code>optional&lt;<code>optional&lt;T&gt;</code>&gt;</code> are involved:</p>

<pre>optional&lt;optional&lt;int&gt;&gt; ooi = optional&lt;int&gt;::nullopt;           <em>// engaged</em>
optional&lt;optional&lt;int&gt;&gt; ooj = optional&lt;optional&lt;int&gt;&gt;::nullopt; <em>// disengaged</em>
</pre>

<pre>void fun(optional&lt;string&gt;);
void fun(optional&lt;int&gt;);

fun(optional&lt;string&gt;::nullopt); <em>// unambiguous: a typeless nullopt would not do</em> 
</pre>

<p>Yet, we choose to propose a typeless tag because we consider the above problems rare and a typeless tag offers a very short notation in other cases:</p>

<pre>optional&lt;string&gt; fun()
{
  optional&lt;int&gt oi = nullopt;  <em>// no ambiguity</em>
  oi = nullopt;                <em>// no ambiguity</em>
  <em>// ...</em>
  return nullopt;              <em>// no ambiguity</em>
}
</pre>

<p>If the typeless tag does not work for you, you can always use the following construct, although at the expense of invoking a (possibly elided) move constructor:</p> 

<pre>optional&lt;optional&lt;int&gt;&gt; ooi = optional&lt;int&gt;{};           <em>// engaged</em>
optional&lt;optional&lt;int&gt;&gt; ooj = optional&lt;optional&lt;int&gt;&gt;{}; <em>// disengaged</em>
</pre>

<pre>void fun(optional&lt;string&gt;);
void fun(optional&lt;int&gt;);

fun(optional&lt;string&gt;{}); <em>// unambiguous</em> 
</pre>

<h3><a name='rationale.access'>Accessing the contained value</a></h3>


<p>It was chosen to use indirection operator because, along with explicit conversion to <code>bool</code>, it is a very common pattern for accessing a value that might not be there: </p>
<pre>if (p) use(*p);</pre>
<p>This pattern is used for all sort of pointers (smart or dumb), and it clearly indicates the fact that the value may be missing and that we return a reference rather than a value.  The indirection operator has risen some objections because it may incorrectly imply that <code>optional</code> is a (possibly smart) pointer, and thus provides shallow copy and comparison semantics. We believe that the cost of potential confusion is overweighed by the benefit of an easy to grasp and intuitive interface for accessing the contained value. </p>

<p>We do not think that providing an implicit conversion to <code>T</code> would be a good choice. First, it would require different way of checking for the epty state; and second, such implicit conversion is not perfect and still requires other means of accessing the contained value if we want to call a member function on it.</p>



<h3><a name='rationale.relops'>Relational operators</a></h3>


<p>One of the design goals of <code>optional</code> is that objects of type <code>optional&lt;T&gt;</code> should be valid elements in STL containers  and usable with STL algorithms (at least if objects of type <code>T</code> are). Equality comparison is essential for <code>optional&lt;T&gt;</code> to model concept <code>Regular</code>. C++ does not have concepts, but being regular is still essential for the type to be effectively used with STL. Ordering is essential if we want to store optional values in associative containers. A number of ways of including the disengaged state in comparisons have been suggested. The ones proposed, have been crafted such that the axioms of equivalence and strict weak ordering are preserved: disengaged <code>optional&lt;T&gt;</code> is simply treated as an additional and unique value of <code>T</code> equal only to itself; this value is always compared as less than any value of <code>T</code>:</p>

<pre>
assert (optional&lt;unsigned&gt;{}  &lt; optional&lt;unsigned&gt;{0});
assert (optional&lt;unsigned&gt;{0} &lt; optional&lt;unsigned&gt;{1});
assert (!(optional&lt;unsigned&gt;{}  &lt; optional&lt;unsigned&gt;{}) );
assert (!(optional&lt;unsigned&gt;{1} &lt; optional&lt;unsigned&gt;{1}));

assert (optional&lt;unsigned&gt;{}  != optional&lt;unsigned&gt;{0});
assert (optional&lt;unsigned&gt;{0} != optional&lt;unsigned&gt;{1});
assert (optional&lt;unsigned&gt;{}  == optional&lt;unsigned&gt;{} );
assert (optional&lt;unsigned&gt;{0} == optional&lt;unsigned&gt;{0});
</pre>

<p>One could also expect comparisons between <code>T</code> and <code>optional&lt;T&gt;</code>. The natural semantics of such comparison would be:</p>

<pre>
template &lt;class T&gt;
bool operator==(const optional&lt;T&gt;&amp; a, const T&amp; b)
{
  return a == make_optional(b);
}
</pre>

<p>We do not propose it because there is no strong motivation for such comparisons. On the contrary, the inadvertent invocation o such comparisons might be disastrous. Consider the following scenario. We have a class that stores the number of passengers:
</p>

<pre>class MyPlan
{
  unsigned passengerCount;
  <em>// ...</em>
};</pre>

<p>At some point we realize that sometimes we will not know the number of passengers: either because we use lazy initialization techniques or because we failed to compute the number. We change the type of the variable:</p>

<pre>class MyPlan
{
  optional&lt;unsigned&gt; passengerCount;
  <em>// ...</em>
};</pre>

<p>And we might expect that compiler will warn us in every place where we try to access the value of <code>passengerCount</code>. However the following comparison will continue to compile although the run-time behaviour will be different than the one expected:</p>

<pre>bool  MyPlan::exceedsCapacity() const
{
  return passengerCount &gt; availableSeats;
  <em>// availableSeats is of type unsigned int</em>
}
</pre>

<p>Since disengaged optional never compares greater than anything, the effect we have is that if we do not know how many passengers there are we report with certainty that their number does not exceed the capacity. For this reason comparison between <code>optional&lt;T&gt;</code> and <code>T</code> are required to be reported as errors at compile-time</p>

<h3><a name='rationale.resetting'>Resetting the optional value</a></h3>


<p>This proposal offers three ways of assigning a new contained value to an optional object:</p>

<pre>optional&lt;int&gt; o;
o = make_optional(1);  <em>// copy/move assignment</em>
o = 1;                 <em>// assignment from T</em>
o.emplace(1);          <em>// emplacement</em> 
</pre>

<p>The first form of assignment is required to make <code>optional</code> a regular object, useable in STL. We need the second form in order to reflect the fact that <code>optional&lt;T&gt;</code> is a wrapper for <code>T</code> and hence it should behave as <code>T</code> as much as possible. Also, when <code>optional&lt;T&gt;</code> is viewed as <code>T</code> with one additional value, we want the values of <code>T</code> to be directly assignable to <code>optional&lt;T&gt;</code>. In addition, we need the second form to allow the interoperability with function <code>std::tie</code> as shown above. The two forms differ only by syntax. Their semantics are practically the same: if <code>o</code> is disengaged, call <code>T</code>'s copy/move constructor to initialize the contained value; otherwise use <code>T</code>'s copy/move assignment to modify the contained value (here, we skip the cases where the right-hand side optional object is disengaged). The third option, using function <code>emplace</code> is different in semantics, which is: destroy the contained value (if engaged) and create anew. It does not require that the contained value is even a moveable type, and guarantees no copying/moving.
 </p>

 
<h3><a name='rationale.emplace'>Tag <code>emplace</code></a></h3>

<p>This proposal provides an 'in-place' constructor that forwards (perfectly) the arguments provided to <code>optional</code>'s constructor into the constructor of <code>T</code>. In order to trigger this constructor one has to use the tag struct <code>emplace</code>. We need the extra tag to disambiguate certain situations, like calling <code>optional</code>'s default constructor and requesting <code>T</code>'s default construction:</p>

<pre>optional&lt;Big&gt; ob{emplace, "1"}; <em>// calls Big{"1"} in place (no moving)</em>
optional&lt;Big&gt; oc{emplace};      <em>// calls Big{} in place (no moving)</em>
optional&lt;Big&gt; od{};             <em>// creates a disengaged optional</em>
</pre>

<p>The name, suggested by Alberto Ganesh Barbati, is consistent with member functions of containers (and <code>optional</code> itself), which also indicate similar purpose. On the other hand, it may appear uncomfortable that <code>emplace</code> becomes overloaded in <code>std</code>: it is now a member funciton in many container type as well as a tag. If this is considered a serious issue, the tag could be renamed to <code>in_place</code>.</p>


 
<h3><a name='rationale.requirements'>Requirements on <code>T</code></a></h3>

<p>Class template <code>optional</code> imposes little requirements on <code>T</code>: it has to be either an lvalue reference type, or a complete object type satysfying the requirements of <code>Destructible</code>. It is the particular operations on <code>optional&lt;T&gt;</code> that impose requirements on <code>T</code>: <code>optional&lt;T&gt;</code>'s move constructor requires that <code>T</code> is <code>MoveConstructible</code>, <code>optional&lt;T&gt;</code>'s copy constructor requires that <code>T</code> is <code>CopyConstructible</code>, and so on. This is because <code>optional&lt;T&gt;</code> is a wrapper for <code>T</code>: it should resemble <code>T</code> as much as possible. If <code>T</code> is <code>EqualityComparable</code> then (and only then) we expect <code>optional&lt;T&gt;</code> to be <code>EqualityComparable</code>. </p>



<h3><a name='rationale.refs'>Optional references</a></h3>


<p>This proposal also contains optional references. These entities are surprising to many people because they do not appear to add any more functionality than pointers do. There exist though a couple of arguments in favour optional references:</p>

<ul>
<li><code>optional&lt;T&gt;</code> can be used in generic code, were <code>T</code> can be either a reference or an object. </li>
<li>It is slightly easier to pass arguments to functions, beacause addressof operator is not required. </li>

<li>Raw pointers historically add confusion in the sense that it is not clear whether we should delete the value they point to or not, as well as whether we should expect <code>nullptr</code> or not. With optional references the answer to these questions is obvious.</li>
</ul>


<h3><a name='rationale.ref.assign'>No assignment for optional references</a></h3>

<p>In this proposal, optional references provide no assignment from <code>T&amp;</code> or <code>optional&lt;T&amp;&gt;</code>. This is because whatever semantics for such assignment is chosen, it is confusing to many programmers. Optional reference can be seen as a reference with postponed initialization. In this case, assignment (to engaged optional reference) should have deep copy semantics: it should assign value to the referred object. On the other hand, an optional reference can be seen as a pointer with different syntax. In this case the assignment (to engaged optional reference) should change the reference, so that it refers to the new object. Neither of these models appears more valid than the other, so we disable assignment to avoid any confusion. In exchange, we provide member function <code>emplace</code>, which provides the 'pointer with special syntax' semantics. The other semantics can be implemented by using the following idiom:</p>

<pre>void assign_norebind(optional&lt;T&amp;&gt;&amp; optref, T&amp; obj)
{
  if (optref) *optref = obj;
  else        optref.emplace(obj);
}
</pre>

<p>The choice not to provide any assignment is based on the observation that any semantics of such assignment is counterintuitive to some people. If allowed, the assignment is likely to cause run-time surprises. We choose to move the surprise from run-time to compile-time. </p>

<p>Some people still expressed disappointment that optional references are not <code>CopyAssignable</code>, and they would rather have the assignment back regardless of the semantics. If the feedback from the LWG is that optional references should be <code>CopyAssignable</code>, we consider providing copy and move assignment with reference rebinding semantics (the ones offered by member function <code>emplace</code>), but still prohibit the direct assignment from a reference:</p>

<pre><em>// backup proposal</em>
int i = 0;
int j = 1;
optional&lt;int&amp;&gt; ori;
optional&lt;int&amp;&gt; orj = j;

*orj = 2;
assert (j == 2);

ori = i; <em>// ERROR: no assignment from int&amp;</em>
ori = {i}; <em>// OK: assignemnt from optional&lt;int&amp;&gt;</em>

orj = ori; <em>// OK: rebinding assignemnt from optional&lt;int&amp;&gt;</em>
*orj = 4;
assert (j == 2);
assert (i == 4);
</pre>


<h3><a name='rationale.rref.binding'>No rvalue binding for optional references</a></h3>

<p>Optional referencs cannot provide an essential feature of native references: extending the life-time of temporaries (rvalues). Temporaries can be bound to (1) rvalue references and to (2) lvalue references to const. In order to avoid dangling reference problems we need to prevent either type of binfing to optional references. In order to prevent the former, we disallow optional rvalue references altogether. We are not aware of any practical use case for such entities. Since optional lvalue references to const appear useful, we avoid the rvalue binding problem by requiring implementations to "poison" rvalue reference constructors for optional lvalue references to const. This may appear surprising as it is inconsistent with normal (non-optional) reference behavior:</p>

<pre>const int&amp; nr = int{1};           <em>// ok</em>
optional&lt;const int&&gt; or = int{1}; <em>// error: int&amp;&amp; ctor deleted</em>
</pre>

<!--
Sometimes this behavior may get really surprising:

<pre>int mi = 1;                      <em>// a global </em>
const int ci = mi;               <em>// a global </em>
optional&lt;const int&&gt; oci = ci;   <em>// ok</em>

const int cj = 1;                <em>// a compile-time constant</em>
optional&lt;const int&&gt; ocj = cj;   <em>// compile-time error: binding to temporary</em>
</pre>

<p>This fails, at least in GCC, because the compiler needs to create a temporary (as <code>cj</code> has no storage).</p> -->

<h3><a name='rationale.noexcept'>Exception specifications</a></h3>


<p>First draft of this revision required an aggressive usage of conditional <code>noexcept</code> specifications for nearly every, member- or non-member-, function in the interface. For instance equality comparison was to be declared as:</p>

<pre>template &lt;class T&gt;
  bool operator==(const optional&lt;T&gt;&amp; lhs, const optional&lt;T&gt;&amp rhs)
  noexcept(noexcept(*lhs == *rhs));
</pre>

<p>This was based on one of our goals: that we want <code>optional&lt;T&gt;</code> to be applicable wherever <code>T</code> is applicable in as many situations as reasonably possible. One such situation occurs where no-throw operations of objects of type <code>T</code> are used to implement a strong exception safety guarantee of some operations. We would like objects of type <code>optional&lt;T&gt;</code> to be also useable in such cases. However, we do not propose this aggressive conditional no-throw guarantees at this time in order for the proposed library component to adhere to the current Library guidlines for conditional <code>noexcept</code>: it is currently only used in move constructor, move assignment and <code>swap</code>. One exception to this rule, we think could be made for optional's move constructor and assignment from type <code>T&amp;&amp;</code>, however we still do not propose this at this time in order to avoid controversy.</p>

<p>Constructors and mutating functions that disengage an optional object are required to be <code>noexcept(true)</code>: they only call <code>T</code>'s destructor and impose no precondition on optional object's or contained value's state. The same applies to the observers that check the disengaged/engaged state.</p>

<p>The observers that access the contained value (or address, for optional references), following the guidelines from N3248<sup>[6]</sup>, are declared as <code>noexcept(false)</code> because they impose a precondition that optional object shall be engaged. These operations are still required not to throw exceptions.</p>

<p>In general, operations on optional objects only throw, when operations delegated to the contained value throw.</p>

<p>Nearly all operations on opeional references are <code>noexcept(true)</code>. This is because optional reference is almost a pointer (with a different interface), and can be used as a pointer to implement strong exception and therefore the guarantee. </p>



<h3><a name='rationale.constexpr'>Constexpr constructors</a></h3>


<p>There are two purposes of making functions and especially constructors <code>constexpr</code>: </p>

<ol>
<li>to enable constant-initialization,</li>
<li>to make the type literal and thereby useful in static contexts.</li>
</ol>

<p>This proposal only aims at the first of the two goals. We can imagine use cases where a global optional object is initialized in two phases: first to a disengaged state in static-initialization phase, and second, after the program (function <code>main</code>) has started, to the engaged state by initializing the contained value with arguments available only at runtime. This also enables constant initialization for other types that contain optional objects. </p>

<p>Making <code>optional&lt;T&gt;</code> a literal-type in general is impossible: the destructor cannot be trivial because it has to execute an operation that can be conceptually described as:</p>

<pre>
~optional() {
  if (is_engaged()) destroy_contained_value();
}
</pre>

<p>It is still possible to make the destructor trivial for <code>T</code>'s which provide a trivial destructor themselves, and we know an efficient implementation of such <code>optional&lt;T&gt;</code> with compile-time interface &mdash; except for copy constructor and move constructor &mdash; is possible. However, since such requirement is very restrictive on implementations, and since we cannot think of any convincing use case for a full compile-time interface, we do not propose it at this time. We believe that if you are able to determine at compile-time whether you need an engaged or disengaged <code>optional&lt;T&gt;</code>, you probably need <code>T</code> alone or no value whatsoever.</p> 

<p>Making an optional reference a literal type, on the other hand, is possible and fairly easy; but again, we cannot think of a practical use-case for it, so here also we only propose to make <code>constexpr</code> the initialization to disengaged state.</p>



<h3><a name='rationale.moved_from'>Moved-from state</a></h3>

<p>When a disengaged optional object is moved from (i.e., when it is the source object of move constructor or move assignment) its state does not change. When an engaged object is moved from, we move the contained value, but leave the optional object engaged. A moved-from contained value is still valid (although possibly not specified), so it is fine to consider such optional object engaged. An alternative approach would be to destroy the contained value and make the moved-from optional object disengaged. However, we do not propose this for performance reasons.</p>

<p>In contexts, like returning by value, where you need to call the destructor the second after the move, it does not matter, but in cases where you request the move explicitly and intend to assign a new value in the next step, and if <code>T</code> does not provide an efficient move, the chosen approach saves an unnecessary destructor and constructor call:</p>

<pre>optional&lt;array&lt;Big&gt;&gt; oo = ... <em>// array doesn't have efficient move</em>
op = std::move(oo);
oo = std::move(tmp);
</pre>

<p>The fact that the moved-from optional is not disengaged may look "uncomfortable" at first, but this is an invalid epectation. The only thing that can be legitimately expected of a moved from object (optional object, in particular) is that it can be assigned to or destroyed without causing any resource leak or undefined behavior.</p>



<h3><a name='rationale.io'>IO operations</a></h3>


<p>The proposed interface for optional values does not contain IO operations: <code>operator&lt;&lt;</code> and <code>operator&gt;&gt;</code>. While we believe that they would be a useful addition to the interface of optional objects, we also observe that there are some technical obstacles in providing them, and we choose not to propose them at this time.</p>

<p>One can imagine a couple of ways in which IO-operations for any streamable type <code>T</code> could be expected to work. The differences are mostly the consequence of different conceptual models of optional types, as well as different use cases that programmers may face. Below we list the possible ways of outputting the value of optional object.</p>

<ol>
<li>Output the contained value if engaged; otherwise enter an undefined behaviour (as programmer error).</li>
<li>Output the contained value if engaged; otherwise output nothing.</li>
<li>Output the contained value if engaged; otherwise output some special sequence of characters.</li>
<li>Output something like <code>"OPT[<var>v</var>]"</code>, where <code><var>v</var></code> represents the contained value, if engaged; otherwise output something like <code>"OPT[]"</code>.</li>
</ol>

<p>The first option is a consequence of the model where <code>optional&lt;T&gt;</code> is a <code>T</code> with deferred initialization, but which is still initialized before first usage. This is not the model that we advocate, so this behavior of <code>operator&lt;&lt;</code> is rejected. However this behavior can be achieved by accessing the contained value of optional object on each usage:</p>

<pre>optional&lt;int&gt; oi;
initialize(oi);
cin &gt;&gt; (*oi);
cout &lt;&lt; (*oi);
</pre>


<p>The second option appears useful in certain contexts, where we want optional objects to indicate some supplementary, often missing, information:</p>

<pre>struct FlatNumber {
  unsigned number_;
  optional&lt;char&gt; letter_;
};

ostream&amp; operator&lt;&lt;( ostream&amp; out, FlatNumber n ) {
  return out &lt;&lt; n.number_ &lt;&lt; n.letter_;
}

<em>// outputs "10", "11", "11A", ...</em> 
</pre>


<p>However, in general the results would be ambiguous. Does output <code>"1&nbsp;0"</code> indicate two engaged <code>optional&lt;int&gt;</code>s, or three, one of which (which one?) is disengaged, or 77 <code>optional&lt;int&gt;</code>s? Or are these perhaps two <code>int</code>s? Also, It is not possible to implement a consistent <code>operator&gt;&gt;</code> in this case. It may not be a problem itself, and providing only one operator is not a precedent in the standard (consider <code>std::thread::id</code>); alternatively, <code>operator&gt;&gt;</code> could be implemented inconsistently: by simply calling <code>T</code>'s <code>operator&gt;&gt;</code>.  
</p>   

<p>The third choice appears attractive at first glance, but there is no good representation for the special sequence that would produce no ambiguities. Whatever sequence we choose, it is also a valid representtion of <code>std::string</code>; thus if we need to interpret the special sequence, say <code>"~~~"</code> as <code>optional&lt;string&gt;</code>, we do not know if it is a disengaged object, or engaged one with contained value of <code>"~~~"</code>. On the other hand, some people have argued that this ambiguity is worth the usefulness of a simple tool for logging.
</p>

<p>While the fourth choice presented above still comes with some similar ambiguities, it is posssible to implement a variant thereof that is not ambiguous. Such solution has been implemented in Boost.Tuple library<sup>[5]</sup>: user has to register a sequence of letters that represent "an opening bracket" of the optional object's contained value, and similarly register an another sequence for representing a "closing bracket." This would be the user's responsibility to make sure that the chosen sequences are unambiguous, if default sequences (e.g., <code>"["</code> and <code>"]"</code>) do not suffice. However, this solution is not without certain controversy.</p>

<p>Currently all streamable types in the library have a nice property that string representation that is streamed out or read in is similar to the format of literals in C++ used to initialize variables. Thus, whatever you type into the console that you intend your program to read, could be equally well typed directly in the C++ code as a literal &mdash; of course, to certain extent. The text that the program requires of users to read and type is simply nice.</p>

<p>This controversy is charachteristic not only of <code>optional</code>. Library components like containers, pairs, tuples face the same issue. At present IO operations are not provided for these types. Our preference for <code>optional</code> is to provide an IO solution compatible with this for containers, pairs and tuples, therefore at tis point we refrain from proposing a solution for <code>optional</code> alone.</p>



<h3>Type requirements <code>NullableProxy</code></h3>

<p>Along with the developement of this proposal, we observe that certain abstraction is common to optional objects, as well as to raw and smart pointers, and is useful enough to provide type requirements for certain class of algorithms. We call this concept <code>NullableProxy</code>. Basically the concept indicates that a type is a 'proxy' for another type. The operations allowed are: checking if there exists an object that our proxy can indirect us to and the indirection operation. The operations can be summarized by the following use-case:</p>

<pre>
temmplate &lt;class NullableProxy&gt;
void test(NullableProxy&amp;&amp; np)
{
  if (np)              <em>// 'has-object' check</em>
    auto&amp;&amp; obj = *np;  <em>// object access</em>
  if (!np) {}          <em>// 'doesn't have object'</em>
}
</pre>

<p>These requirements are sufficient to specify a couple of algorithms (not proposed), like the one below: </p>

<pre>template &lt;typename NullableProxy&gt;
<em>// enable_if: decltype(*declval&lt;NullableProxy&gt;()) is EqualityComparable</em>
bool equal_pointees( const NullableProxy&amp; x, const NullableProxy&amp; y )
{
  return bool(x) != bool(y) ? false : ( x ? *x == *y : true );
}
</pre>

<p>This is exactly the logic for the equality comparison of optional values, and could be used as an implementation of <code>optional&lt;T&gt;::operator==</code>. A similar algorithm for less-than comparison can be specified. The third example is function <code>get_value_or</code> discussed below.</p>

<p>Requirements <code>NullableProxy</code> overlap with requirements <code>NullablePointer</code>. Their common part could be extracted to separate requirements, say <code>Nullable</code>, but these requirements are to small to be useful alone for anything.</p>

<p>We do not propose to add <code>NullableProxy</code> to Library at this time, but we consider it a useful future addition.</p>



<h3><a name='rationale.get_value_or'>Function <code>get_value_or</code></a></h3>


<p>This function template returns a value stored by the <code>optional</code> object if it is engaged, and if not, it falls back to the default value specified in the second argument. This method for specifying default values on the fly rather than tying the default values to the type is based on the observation that different contexts or usages require different default values for the same type. For instance the default value for <code>int</code> can be 0 or -1. The callee might not know what value the caller considers special, so it returns the lack of the requested value explicitly. The caller may be better suited to make the choice what special value to use.</p>

<pre>
optional&lt;int&gt; queryDB(std::string);
void setPieceCount(int);
void setMaxCount(int);

setPieceCount( get_value_or(queryDB("select piece_count from ..."), 0) );
setMaxCount( get_value_or(queryDB("select max_count from ..."), numeric_limits&lt;int&gt;::max()) );
</pre>

<p>The decision to provide this function is controversial itself. As pointed out by Robert Ramey, the goal of the <code>optional</code> is to make the lack of the value explicit. Its syntax forces two control paths; therefore we will typically see an <code>if</code>-statement (or similar branching instruction) wherever <code>optional</code> is used. This is considered an improvement in correctness. On the other hand, using the default value appears to conflict with the above idea. One other argument against providing it is that in many cases you can use a ternary conditional operator instead:</p>

<pre>auto&amp;&amp; cnt = queryDB("select piece_count from ...");
setPieceCount(cnt ? *cnt : 0);

auto&amp;&amp; max = queryDB("select max_count from ...");
setMaxCount(max ? std::move(*max) : numeric_limits&lt;int&gt;::max());
</pre>

<p>However, in case optional objects are returned by value and immediately consumed, the ternary operator syntax requires more typing and explicit <code>move</code>.</p>

<p>We did not make it a member function for two reasons. (1) It can be implemented by using only the public interface of <code>optional</code>. (2) This function template could be equally well be applied to any type satysfying the requirements of <code>NullableProxy</code>. In this proposal, function <code>get_value_or</code> is defined only for <code>optional</code>s but being a non-member function allows this extension in the future.
</p>

<p>The second argument in the function template's signature is not <code>T</code> but any type convertible to <code>T</code>:</p>

<pre>
template &lt;class T, class V&gt; 
  typename decay&lt;T&gt;::type get_value_or(const optional&lt;T&gt;&amp; <var>op</var>, V&amp;&amp; <var>v</var>);
template &lt;class T, class V&gt; 
  typename decay&lt;T&gt;::type get_value_or(optional&lt;T&gt;&amp;&amp; <var>op</var>, V&amp;&amp; <var>v</var>);
</pre>

<p>This allows for a certain run-time optimization. In the following example:</p>

<pre>optional&lt;string&gt; op{"cat"};
string ans = get_value_or(op, "dog");
</pre>

<p>Because the optional object is engaged, we do not need the fallback value and therefore to convert the string literal <code>"dog"</code> into type <code>string</code>.</p>

<p>The function also works for optional references. In this case the returned value is created from the referred object; a copy is returned. It has been argued that the function should return by constant reference rather than value, which would avoid copy overhead in certain situations:</p>

<pre>void observe(const X&amp; x);

optional&lt;X&gt; ox { <em>/* ... */</em> };
observe( get_value_or(ox, X{args}) );   <em>// unnecessary copy</em>
</pre>

<p>However, the benefit of the function <code>get_value_or</code> is only visible when the optional object is provided as a temporary (without the name); otherwise, a ternary operator is equally useful:</p>

<pre>optional&lt;X&gt; ox { <em>/* ... */</em> };
observe(ox ? *ok : X{args});            <em>// no copy</em>
</pre>

<p>Also, returning by reference would be likely to render a dangling reference, in case the optional object is disengaged, because the second argument is typically a temporary:</p>

<pre>
optional&lt;X&gt; ox {nullopt};
auto&amp;&amp; x = get_value_or(ox, X{args});
cout &lt;&lt; x;                             <em> // x is dangling!</em>
</pre>

<p>It has also been suggested (by Luc Danton) that function <code>get_value_or&lt;T, V&gt;</code> should return type <code>decay&lt;common_type&lt;T, V&gt;::type&gt;::type</code> rather than <code>decay&lt;T&gt;::type</code>. This would avoid certain problems, such as loss of accuracy on arithmetic types:</p>

<pre><em>// not proposed</em>
std::optional&lt;int&gt; op = <em>/* ... */</em>;
long gl = <em>/* ... */</em>;

auto lossless = get_value_or(op, gl);   <em>// lossless deduced as long rather than int</em>
</pre>

<p>However, we did not find many practical use cases for this extension, so we do not propose is at this time.</p>







<h3><a name='rationale.make_optional'>Function <code>make_optional</code></a></h3>

<p>We also propose a helper function <code>make_optional</code>. Its semantics is closer to that of <code>make_pair</code> or <code>make_tuple</code> than that of <code>make_shared</code>. You can use it in order for the type of the optional to be deduced:</p>

<pre>int i = 1;
auto oi = make_optional(i);          <em>// decltype(oi) == optional&lt;int&gt;</em>
auto ri = make_optional(ref(i));     <em>// decltype(ri) == optional&lt;int&amp;&gt;</em>
</pre>

<p>This may occasionally be useful when you need to pick the right overload and not type the type of the optional by hand: </p>

<pre>void fun(optional&lt;complex&lt;double&gt;&gt;);
void fun(Current);                   <em>// complex is convertible to Current</em>

complex&lt;double&gt; c{0.0, 0.1};
fun(c);                              <em>// ambiguous</em>
fun({c});                            <em>// ambiguous</em>
fun(make_optional(c));               <em>// picks first overload</em>
</pre>

<p>This is not very useful in return statements, as long as the converting constructor from <code>T</code> is implicit, because you can always use the brace syntax:</p>

<pre>optional&lt;complex&lt;double&gt;&gt; findC()
{
  complex&lt;double&gt; c{0.0, 0.1};
  return {c};
}
</pre>

<p><code>make_shared</code>-like function does not appear to be useful at all: it is no different than manually creating a temporary optional object:</p>

<pre><em>// not proposed</em>
fun( make_optional&lt;Rational&gt;(1, 2) );
fun( optional&lt;Rational&gt;{1, 2} );     <em>// same as above</em>
</pre>

<p>It would also not be a good alternative for tagged placement constructor, because using it would require type <code>T</code> to be <code>MoveConstructible</code>:</p>

<pre><em>// not proposed</em>
auto og = make_optional&lt;Guard&gt;("arg1"); <em>// ERROR: Guard is not MoveConstructible</em>
</pre>

<p>Such solution works for <code>shared_ptr</code> only because its copy constructor is shallow. One useful variant of <code>shared_ptr</code>-like <code>make_optional</code> would be a function that either creates an engaged or a disengaged optional based on some boolean condition:</p>

<pre><em>// not proposed</em>
return make_optional_if&lt;Rational&gt;(good(i) &amp;&amp; not_bad(j), i, j);

<em>// same as:</em>
if (good(i) &amp;&amp; not_bad(j)) {
  return {i, j};
}
else {
  return nullopt;
}

<em>// same as:</em>
optional&lt;Rational&gt; or = nullopt;
if (good(i) &amp;&amp; not_bad(j)) or.emplace(i, j);
return or; <em>// move-construct on return</em>
</pre>

<p>Since this use case is rare, and the function call not that elegant, and a two-liner alternative exists, we do not propose it.</p>

<h3><a name='rationale.conversion'>"Copy initialization forwarding"</a></h3>

<p>At some point the following goal was considered for <code>optional</code>; it is the property that could informally be called "copy initialization forwarding". It is somewhat similar to the one-argument version of perfect forwarding constructor; i.e., if a given initializer can be used to copy-initialize objects of type <code>T</code>, it should also be possible to to use it to copy-initialize objects of type <code>optional&lt;T&gt;</code> with the same samantics as initializing object of type <code>T</code>. This goal cannot be achieved in 100% without severely compromising other design goals. For instance, we cannot guarantee the following: </p>

<pre>T x = {};             <em>// "{}" is the initializer; x is value-initialized</em>
optional&lt;T&gt; ox = {};  <em>// same initializer; contained value not initialized</em>

assert (x == *ox);    <em>// not guaranteed!</em>
</pre>

<p>Apart from this default initialization case, and a couple of others (cocncerning initializer-list), "copy initialization forwarding" could be provided for <code>optional</code>.</p>

<p>Since <code>optional&lt;T&gt;</code> can be thought of as an "almost <code>T</code>", one could expect that if the following works:</p>

<pre>void fun(std::string s);
fun("text");
</pre>

<p>the following should also work:</p>

<pre>void gun(optional&lt;std::string&gt; s);
gun("text");
</pre>

<p>However, naively implementing a converting constructor would also enable a non-explicit converting constructor from any type <code>U</code> to type <code>optional&lt;T&gt;</code> for any type <code>T</code>. This would turn some types that are explicitly constructible into optional types that are implicitly constructible. Consider:
</p>


<pre>void explicit_conv( int * ptr ) {
  unique_ptr&lt;int&gt; v = ptr;           <em>// ILLEGAL</em> 
}

void implicit_conv( int * ptr ) {
  optional&lt;unique_ptr&lt;int&gt;&gt; v = ptr; <em>// LEGAL</em>
}</pre>

<p>In order to make the former example work on the one hand and to prevent the problem with the latter example on the other, we considered a solution that could be informally called a conditionally-explicit converting constructor. We could achieve this by specifying two constructor templates with identical template and function parameters, one explicit and one non-explicit, and make them mutually exclusive by means of SFINAE:</p>

<pre>
template &lt;class U&gt; 
  <em>// enable_if: Constructible&lt;T, U&amp;&amp;&gt; &amp;&amp; !Convertible&lt;U&amp;&amp;, T&gt;</em>
  explicit optional&lt;T&gt;::optional(U&amp;&amp;);
   
template &lt;class U&gt; 
  <em>// enable_if: Convertible&lt;U&amp;&amp;, T&gt;</em>
  optional&lt;T&gt;::optional(U&amp;&amp;);
</pre>


<p>Such concept-like behaviour as used above can be implemented in C++ with type traits and <code>enable_if</code>. It was noted, however, that the existence of such converting constructor would cause unexpected ambiguities in overload resolution. Consider the following scenario. We start from a working program:</p>

<pre><em>// library</em>
void fun(string const&amp; s);

<em>// usage</em>
fun("hello");
</pre>

<p>At some point we decide to add a second overload that accepts an optional string:</p>

<pre><em>// library</em>
void fun(string const&amp; s);
void fun(optional&lt;string&gt; const&amp; s);   <em>// new overload</em>

<em>// usage</em>
fun("hello");                          <em>// ERROR: ambiguity </em>
</pre>

<p>Does it make sense to add an overload for optional rather than substituting it for the original? It might be useful for performance reasons: if you already have <code>string</code> it is cheaper to bind it directly to <code>string const&amp;</code> than to create a temporary optional object and trigger the copy constructor of <code>string</code>:</p>

<pre><em>// library</em>
void fun(optional&lt;string&gt; const&amp; s);   <em>// only this fun</em>

<em>// usage</em>
string s = "hello";
fun(s);                                <em>// copy ctor invoked!</em>
</pre>


<p>This example shows how an implicit conversion can cause an inadvertent and unexpected (potentially expensive) copy constructor. For this reason we do not propose a converting constructor from arbitrary type <code>U</code>. (Although we do propose a converting constructor from <code>T</code>.)</p>


<h3><a name='rationale.initializer_list'>Handling <code>initializer_list</code></a></h3>

<p>Another feature worth considering is a "sequence constructor" (one that takes <code>initializer_list</code> as its argument). It would be enabled (in <code>enable_if</code> sense) only for these <code>T</code>s that themself provide a sequence constructor. This would be usefult to fully support two features we already mentioned above (but chose not to propose).</p>

<p>First, our goal of "copy initialization forwarding" for <code>optional</code> also needs to address the following usages of <code>initializer_list</code>:
</p>

<pre>vector&lt;int&gt; v = {1, 2, 4, 8};
optional&lt;vector&lt;int&gt;&gt; ov = {1, 2, 4, 8};

assert (v == *ov);
</pre>

<p>This is not only a syntactical convenience. It also avoids subtle bugs. When perfect forwarding constructor is implemented naively with one variadic constructor, optional vector initialization may render surprising result:</p>

<pre>optional&lt;vector&lt;int&gt;&gt; ov = {3, 1};

assert (*ov == vector{3, 1});    // FAILS!
assert (*ov == vector{1, 1, 1}); // TRUE!
</pre>

<p>However this sequence constructor feature is incompatible with another one: default constructor creating a disengaged optional. This is because, as outlined in the former example, initializer <code>{}</code>, that looks like 0-element list, is in fact interpretted as the request for value-initialization (default constructor call). This may hit programmers that use initializer list in "generic" context:</p>

<pre>
template &lt;class ...A&gt; <em>// enable_if: every A is int</em>
void fwd(const A&&... a)
{
  optional&lt;vector&lt;int&gt;&gt; o = {a...};
  assert (bool(o)); <em>// not true for empty a</em>
}
</pre>

<p>If this feature were to be added, we would need to provide an assignment from initializer list and variadic 'emplacement' constructor with the first forwarded argument being <code>initializer_list</code>:</p>

<pre>ov = {1, 2, 4, 8};

allocator&lt;int&gt; a;
optional&lt;vector&lt;int&gt;&gt; ou { emplace, {1, 2, 4, 8}, a };

assert (ou == ov);
</pre>


<p>Since we are not proposing neither perfect forwarding constructor, nor the "copy initialization forwarding", we are also not proposing the sequence constructor. However, in this proposal, the following constructs work:</p>

<pre>optional&lt;vector&lt;int&gt;&gt; ov{emplace, {3, 1}};
assert (*ov == vector{3, 1});

ov.emplace({3, 1});
assert (*ov == vector{3, 1});
</pre>


<h3><a name='rationale.optional_optional'><code>optional&lt;optional&lt;T&gt;&gt;</code></a></h3>


<p>The necessity to create a "double" optional explicitly does not occur often. Such type may appear though in generic contexts where we create <code>optional&lt;V&gt;</code> and <code>V</code> only happens to be <code>optional&lt;T&gt;</code>. Some special behavior to be observed in this situation is the following. When copy-initializing with <code>nullopt</code>, the "outermost" optional is initialized to disengaged state. Thus, changing function argument from <code>optional&lt;T&gt;</code> to <code>optional&lt;optional&lt;T&gt;&gt;</code> will silently break the code in places where the argument passed to function happens to be of type <code>nullopt_t</code>:</p>

<pre><em>// before change</em>
void fun(optional&lt;T&gt; v) {
  process(v);
}

fun(nullopt); <em>// process() called</em>

<em>// after change</em>
void fun(optional&lt;optional&lt;T&gt;&gt; v) {
  if (v) process(*v);
  else   doSthElse();
}

fun(nullopt); <em>// process() not called!</em>
</pre>

<p>This issue would not arise if <code>nullopt</code> were <code>T</code>-specific:</p> 

<pre>
fun(optional&lt;T&gt;::nullopt);            <em>// process() called</em>
fun(optional&lt;optional&lt;T&gt;&gt;::nullopt);  <em>// process() not called</em>
</pre>


<p>Since <code>T</code>-dependent <code>nullopt</code> is not proposed, in order to creae an engaged optional containing a disengaged optional, one needs to use one of the following constructs:</p>

<pre>
optional&lt;optional&lt;T&gt;&gt; ot {emplace};
optional&lt;optional&lt;T&gt;&gt; ou {emplace, nullopt};
optional&lt;optional&lt;T&gt;&gt; ov {optional&lt;T&gt;{}};
</pre>

<p>Also note that <code>make_optional</code> will create a "double" optional when called with optional argument:</p>

<pre>optional&lt;int&gt; oi;
auto ooi = make_optional(oi);
static_assert( is_same&lt;optional&lt;optional&lt;int&gt;&gt;, decltype(ooi)&gt;::value, "");

</pre>



<h3><a name='rationale.conditional.init'>Conditional initialization to engaged state</a></h3>


<p>It has been suggested, and in fact implemented in Boost.Optional, that <code>optional</code> shall have an another constructor with the first argument of type <code>bool</code>. The value of this argument should be used to determine whether the object should be disengaged, or engaged using the remaining arguments. If we wanted to provide it in <code>optional</code> and disampiguate the situations where the contained value is also initialized with the first argument of type <code>bool</code>, it could be easily done by providing a yet another tag (similar to <code>emplace_t</code>):</p>

<pre>bool doIt = false;
tr2::optional&lt;string&gt; opstr1{ tr2::only_if(doIt), 3, 'x' }; 
<em>// disengaged</em>

doIt = true;
tr2::optional&lt;string&gt; opstr2{ tr2::only_if(doIt), 3, 'x' }; 
<em>// contained value is "xxx"</em>
</pre>

<p>However, we do not see a practical use case for this usage. Undoubtadly, it spares you from an explicit if-statement and a two-phase initialization of the optional object, but then it appears obvious that at some time you need to check the value of <code>doIt</code> anyway, because you do not even know the state of the optional object. It is at that time that you may as well decide to initialize the contained value:</p>

<pre>optional&lt;string&gt; process( bool doIt )
{
  fun1(doIt);
  optional&lt;string&gt; optstr;
  
  if (doIt) { <em> // we ned an if to conditionally call fun2()</em>
    fun2();
    optstr.emplace(3, 'x');
  }
  
  return optstr;
}</pre>

<p>Also, even if you create optional as disengaged in the conditional constructor, you still have to compute the values of the arguments that you could potentially use to initialize the contained value, so the two-phase initialization may look more attractive.
</p>

<p>For these reasons we do not propose such conditional constructor at this point. However, there appears to be no difficulty in adding it if we find convincing use cases.</p>



<h2><a name='wording'>Proposed wording</a></h2>



<p>Add new header in Table 14 (C++ library headers).</p>

<blockquote class="std">
<table>
<caption>Table 14 &mdash; C++ library headers</caption>
<tbody>
<tr>
<td><code>&lt;algorithm&gt;</code></td> <td><code>&lt;fstream&gt;</code></td> <td><code>&lt;list&gt;</code></td> <td><code>&lt;ratio&gt;</code></td> <td><code>&lt;tuple&gt;</code></td>

</tr>
<tr>
<td><code>&lt;array&gt;</code></td> <td><code>&lt;functional&gt;</code></td> <td><code>&lt;locale&gt;</code></td> <td><code>&lt;regex&gt;</code></td> <td><code>&lt;typeindex&gt;</code></td>
</tr>
<tr>
<td><code>&lt;atomic&gt;</code></td> <td><code>&lt;future&gt;</code></td> <td><code>&lt;map&gt;</code></td> <td><code>&lt;set&gt;</code></td> <td><code>&lt;typeinfo&gt;</code></td>

</tr>
<tr>
<td><code>&lt;bitset&gt;</code></td> <td><code>&lt;initializer_list&gt;</code></td> <td><code>&lt;memory&gt;</code></td> <td><code>&lt;sstream&gt;</code></td> <td><code>&lt;type_traits&gt;</code></td>
</tr>
<tr>
<td><code>&lt;chrono&gt;</code></td> <td><code>&lt;iomanip&gt;</code></td> <td><code>&lt;mutex&gt;</code></td> <td><code>&lt;stack&gt;</code></td> <td><code>&lt;unordered_map&gt;</code></td>

</tr>
<tr>
<td><code>&lt;codecvt&gt;</code></td> <td><code>&lt;ios&gt;</code></td> <td><code>&lt;new&gt;</code></td> <td><code>&lt;stdexcept&gt;</code></td> <td><code>&lt;unordered_set&gt;</code></td>
</tr>
<tr>
<td><code>&lt;complex&gt;</code></td> <td><code>&lt;iosfwd&gt;</code></td> <td><code>&lt;numeric&gt;</code></td> <td><code>&lt;streambuf&gt;</code></td> <td><code>&lt;utility&gt;</code></td>

</tr>
<tr>
<td><code>&lt;condition_variable&gt;</code></td> <td><code>&lt;iostream&gt;</code></td> <td><ins><code>&lt;optional&gt;</code></ins></td> <td><code>&lt;string&gt;</code></td> <td><code>&lt;valarray&gt;</code></td>
</tr>
<tr>
<td><code>&lt;dequeue&gt;</code></td> <td><code>&lt;istream&gt;</code></td> <td><code>&lt;ostream&gt;</code></td> <td><code>&lt;strstream&gt;</code></td> <td><code>&lt;vector&gt;</code></td>

</tr>
<tr>
<td><code>&lt;exception&gt;</code></td> <td><code>&lt;iterator&gt;</code></td> <td><code>&lt;queue&gt;</code></td> <td><code>&lt;system_error&gt;</code></td> <td><code>&nbsp;</code></td>
</tr>
<tr>
<td><code>&lt;forward_list&gt;</code></td> <td><code>&lt;limits&gt;</code></td> <td><code>&lt;random&gt;</code></td> <td><code>&lt;thread&gt;</code></td> <td><code>&nbsp;</code></td>

</tr>
</tbody>
</table>
</blockquote>


<p>After chapter 20.4 Tuples [tuple], insert a new paragraph. (Chapter [template.bitset] (Class template <code>bitset</code>) becomes 20.6.)</p>
  
 <blockquote class="stdins"> 
<h3><a name="optional">20.5 Optional objects <span style="float:right">[optional]</span></a></h3>


<h4><a name="optional.general">20.5.1 In general <span style="float:right">[optional.general]</span></a></h4>

<p>This subclause describes class template <code>optional</code> that represents <em>optional objects</em>. An <em>optional object for object types</em> is an object that contains the storage for another object and manages the lifetime of this contained object. The contained object may be initialized after the optional object has been initialized, and may be destroyed before the optional object has been destroyed. The initialization state of the contained object is tracked by the optional object. An <em>optional object for lvalue reference types</em> is an object capable of storing the address of another object. The address stored by the optional object can be canged or set to a value that does not represent a valid address. </p>

  
<h4><a name="optional.synop">20.5.2 Header <kbd>&lt;optional&gt;</kbd> synopsis <span style="float:right">[optional.synop]</span></a></h4>

<pre>
namespace std {
namespace experimental {
  // <em><a href="#optional.object">20.5.4</a>, <code>optional</code> for object types</em>
  template &lt;class T&gt; class optional;

  // <em><a href="#optional.lref">20.5.5</a>, <code>optional</code> for lvalue reference types</em>
  template &lt;class T&gt; class optional&lt;T&amp;&gt;;

  // <em><a href="#optional.inplace">20.5.6</a>, In-place construction</em>
  struct emplace_t{};
  constexpr emplace_t emplace{};

  // <em><a href="#optional.nullopt">20.5.7</a>, Disengaged state indicator</em>
  struct nullopt_t{<em>see below</em>};
  constexpr nullopt_t nullopt(<em>unspecified</em>);

  // <em><a href="#optional.relops">20.5.8</a>, Relational operators</em>
  template &lt;class T&gt;
    bool operator==(const optional&lt;T&gt;&amp;, const optional&lt;T&gt;&amp;);
  template &lt;class T&gt;
    bool operator!=(const optional&lt;T&gt;&amp;, const optional&lt;T&gt;&amp;);
  template &lt;class T&gt;
    bool operator&lt;(const optional&lt;T&gt;&amp;, const optional&lt;T&gt;&amp;);
  template &lt;class T&gt;
    bool operator&gt;(const optional&lt;T&gt;&amp;, const optional&lt;T&gt;&amp;);
  template &lt;class T&gt;
    bool operator&lt;=(const optional&lt;T&gt;&amp;, const optional&lt;T&gt;&amp;);
  template &lt;class T&gt;
    bool operator&gt;=(const optional&lt;T&gt;&amp;, const optional&lt;T&gt;&amp;);

  // <em><a href="#optional.nullops">20.5.9</a>, Comparison with <code>nullopt</code></em>
  template &lt;class T&gt; bool operator==(const optional&lt;T&gt;&amp;, nullopt_t) noexcept;
  template &lt;class T&gt; bool operator==(nullopt_t, const optional&lt;T&gt;&amp;) noexcept;
  template &lt;class T&gt; bool operator!=(const optional&lt;T&gt;&amp;, nullopt_t) noexcept;
  template &lt;class T&gt; bool operator!=(nullopt_t, const optional&lt;T&gt;&amp;) noexcept;
  template &lt;class T&gt; bool operator&lt;(const optional&lt;T&gt;&amp;, nullopt_t) noexcept;
  template &lt;class T&gt; bool operator&lt;(nullopt_t, const optional&lt;T&gt;&amp;) noexcept;
  template &lt;class T&gt; bool operator&lt;=(const optional&lt;T&gt;&amp;, nullopt_t) noexcept;
  template &lt;class T&gt; bool operator&lt;=(nullopt_t, const optional&lt;T&gt;&amp;) noexcept;
  template &lt;class T&gt; bool operator&gt;(const optional&lt;T&gt;&amp;, nullopt_t) noexcept;
  template &lt;class T&gt; bool operator&gt;(nullopt_t, const optional&lt;T&gt;&amp;) noexcept;
  template &lt;class T&gt; bool operator&gt;=(const optional&lt;T&gt;&amp;, nullopt_t) noexcept;
  template &lt;class T&gt; bool operator&gt;=(nullopt_t, const optional&lt;T&gt;&amp;) noexcept;

  // <em><a href="#optional.specalg">20.5.10</a>, Poisoned comparison with T</em>
  template &lt;class T&gt; bool operator==(const optional&lt;T&gt;&amp;, const T&amp;) noexcept;
  template &lt;class T&gt; bool operator==(const T&amp;, const optional&lt;T&gt;&amp;) noexcept;
  template &lt;class T&gt; bool operator!=(const optional&lt;T&gt;&amp;, const T&amp;) noexcept;
  template &lt;class T&gt; bool operator!=(const T&amp;, const optional&lt;T&gt;&amp;) noexcept;
  template &lt;class T&gt; bool operator&lt;(const optional&lt;T&gt;&amp;, const T&amp;) noexcept;
  template &lt;class T&gt; bool operator&lt;(const T&amp;, const optional&lt;T&gt;&amp;) noexcept;
  template &lt;class T&gt; bool operator&lt;=(const optional&lt;T&gt;&amp;, const T&amp;) noexcept;
  template &lt;class T&gt; bool operator&lt;=(const T&amp;, const optional&lt;T&gt;&amp;) noexcept;
  template &lt;class T&gt; bool operator&gt;(const optional&lt;T&gt;&amp;, const T&amp;) noexcept;
  template &lt;class T&gt; bool operator&gt;(const T&amp;, const optional&lt;T&gt;&amp;) noexcept;
  template &lt;class T&gt; bool operator&gt;=(const optional&lt;T&gt;&amp;, const T&amp;) noexcept;
  template &lt;class T&gt; bool operator&gt;=(const T&amp;, const optional&lt;T&gt;&amp;) noexcept;

  // <em><a href="#optional.specalg">20.5.11</a>, Specialized algorithms</em>
  template &lt;class T&gt; void swap(optional&lt;T&gt;&amp;, optional&lt;T&gt;&amp;) noexcept(<em>see below</em>);
  template &lt;class T, class V&gt; 
    typename decay&lt;T&gt;::type get_value_or(const optional&lt;T&gt;&amp;, V&amp;&amp;);
  template &lt;class T, class V&gt; 
    typename decay&lt;T&gt;::type get_value_or(optional&lt;T&gt;&amp;&amp;, V&amp;&amp;);
  template &lt;class T&gt;
    optional&lt;<em>see below</em>&gt; make_optional(T&amp;&amp;);
} <em>// namespace experimental</em>
} <em>// namespace std</em>
</pre>
  
  <p>A program that necessitates the instantiation of template <code>optional</code> for an rvalue reference type, or for types <code>emplace_t</code> or <code>nullopt_t</code>, or a possibli cv-qualified reference to types <code>emplace_t</code> or <code>nullopt_t</code> is ill-formed.</p>

<h4><a name="optional.defs">20.5.3 Definitions <span style="float:right">[optional.defs]</span></a></h4>
 
  <p>An instance of <code>optional&lt;T&gt;</code> is said to be <em>disengaged</em> if it has been default constructed, constructed or assigned with a value of type <code>nullopt_t</code>, constructed or assigned with a disengaged optional object of type <code>optional&lt;U&gt;</code>, with <code>U</code> being equal or not to <code>T</code>.
  </p>

  <p>An instance of <code>optional&lt;T&gt;</code> is said to be <em>engaged</em> if it has 
  been modified with member function <code>emplace</code>, constructed with a value of type <code>U</code>, assigned a value of type <code>U</code>, copy-constructed from or assigned with an engaged optional object of type <code>optional&lt;U&gt;</code>, where <code>U</code> is same as or convertible to <code>T</code>. 
  </p>

  <p>Being engaged or disengaged is part of the state optional object's state.</p>
  
  <!-- <p>An <em>optional object for object type</em> is an instance of class <code>optional&lt;T&gt;</code> where <code>T</code> is of object type (3.9).</p>
  
  <p>An <em>optional object for lvalue reference type</em> is an instance of class <code>optional&lt;T&gt;</code> where <code>T</code> is of lvalue reference type.</p>-->
  
  
   <p>In several places in this Clause the expression <code>OnlyExplicitlyConstructible(T, V)</code> is used. All such cases mean the evaluation of the expression:</p>
   
   <pre>std::is_constructible&lt;T, V&gt;::value &amp;&amp; !std::is_convertible&lt;V, T&gt;::value</pre>
 
  
<h4><a name="optional.object">20.5.4 <code>optional</code> for object types <span style="float:right">[optional.object]</span></a></h4>

  
<pre>
namespace std {
namespace experimental {

  template &lt;class T&gt;
  class optional
  {
  public:
    typedef T value_type;

    // <em><a href="#optional.object.ctor">20.5.4.1</a>, constructors</em>
    constexpr optional() noexcept;
    constexpr optional(nullopt_t) noexcept;
    optional(const optional&amp;);
    optional(optional&amp;&amp;) noexcept(<em>see below</em>);
    optional(const T&amp;);
    optional(T&amp;&amp;);<!--
    template &lt;class U&gt; explicit optional(U&amp;&amp;);
    template &lt;class U&gt; optional(U&amp;&amp;);
    template &lt;class U&gt; explicit optional(const optional&lt;U&gt;&amp;);
    template &lt;class U&gt; optional(const optional&lt;U&gt;&amp;);
    template &lt;class U&gt; explicit optional(optional&lt;U&gt;&amp;&amp;);
    template &lt;class U&gt; optional(optional&lt;U&gt;&amp;&amp;);
    template &lt;class U&gt; explicit optional(initializer_list&lt;U&gt;);
    template &lt;class U&gt; optional(initializer_list&lt;U&gt;);-->
    template &lt;class... Args&gt; explicit optional(emplace_t, Args&amp;&amp;...);
    template &lt;class U, class... Args&gt;
      explicit optional(emplace_t, initializer_list&lt;U&gt;, Args&amp;&amp;...);

    // <em><a href="#optional.object.dtor">20.5.4.2</a>, destructor</em>
    ~optional();

    // <em><a href="#optional.object.assign">20.5.4.3</a>, assignment</em>
    optional&amp; operator=(nullopt_t) noexcept;<!--
    optional&amp; operator=(const T&amp;);
    optional&amp; operator=(T&amp;&amp;);-->
    optional&amp; operator=(const optional&amp;);
    optional&amp; operator=(optional&amp;&amp;) noexcept(<em>see below</em>);
    template &lt;class U&gt; optional&amp; operator=(U&amp;&amp;);<!--
    template &lt;class U&gt; optional&amp; operator=(const optional&lt;U&gt;&amp;);
    template &lt;class U&gt; optional&amp; operator=(optional&lt;U&gt;&amp;&amp;);
    template &lt;class U&gt; optional&amp; operator=(initializer_list&lt;U&gt;);-->
    template &lt;class... Args&gt; optional&amp; emplace(Args&amp;&amp;...);
    template &lt;class U, class... Args&gt;
      optional&amp; emplace(initializer_list&lt;U&gt;, Args&amp;&amp;...);

    // <em><a href="#optional.object.swap">20.5.4.4</a>, swap</em>
    void swap(optional&) noexcept(<em>see below</em>);

    // <em><a href="#optional.object.observe">20.5.4.5</a>, observers</em>
    T const* operator -&gt;() const;
    T*       operator -&gt;();
    T const&amp; operator *() const;
    T&amp;       operator *();
    explicit operator bool() const noexcept;<!--T  get_value_or(const T&amp;) const&amp; noexcept(<em>see below</em>);
    T  get_value_or(T&amp;&amp;) &amp;&amp; noexcept(<em>see below</em>);
    T&amp; get_value_or(T&amp;) &amp; noexcept;-->

  <var>private:</var>
    <var>bool init; //</var> <em>exposition only</em>
    <var>T*   val;  //</var> <em>exposition only</em>
  };

} // <em>namespace experimental</em>
} // <em>namespace std</em></pre>

<p>Engaged instances of <code>optional&lt;T&gt;</code> where <code>T</code> is of object type shall contain a value of type <code>T</code> within its own storage. This value is referred to as the <em>contained value</em> of the optional object. Implementations are not permitted to use additional storage, such as dynamic memory, to allocate its contained value.  The contained value shall be allocated in a region of the <code>optional&lt;T&gt;</code> storage suitably aligned for the type <code>T</code>. Initializing the contained value shall put the optional object into engaged state. Destroying the contained value shall put the optional object into disengaged state.</p>

<p>Members <code><var>init</var></code> and <code><var>val</var></code> are provided for exposition only. Implementations need not provide those members. <code><var>init</var></code> indicates whether the <code>optional</code> object's contained value has been initialized (and not yet destroyed); <code><var>val</var></code> points to (a possibly uninitialized) contained value.
  </p>

<p><code>T</code> shall be an object type and shall satisfy the requirements of <code>Destructible</code> (Table 24).</p>

<p>Throughout this subclause term <em>direct-non-list-initialization</em> is used to denote a direct-initialization that is not list-initialization.</p>



<h5><a name="optional.object.ctor">20.5.4.1 Constructors <span style="float:right">[optional.object.ctor]</span></a></h5>

  
  <p class="function">
  <code>constexpr optional&lt;T&gt;::optional() noexcept;</code><br>
  <code>constexpr optional&lt;T&gt;::optional(nullopt_t) noexcept;</code>
  </p>

  <dl class="attribute">
  <dt>Effects:</dt> <dd><p>Constructs a disengaged <code>optional</code> object.</p></dd>
  <dt>Postconditions:</dt> <dd><p><code>bool(*this) == false</code>.</p></dd>
  <dt>Remarks:</dt> <dd><p>No <code>T</code> object referenced is initialized. For every object type <code>T</code> these constructors shall be <code>constexpr</code> constructors (7.1.5).</p></dd>
  </dl>

  
  <p class="function">
  <code>optional&lt;T&gt;::optional(const optional&lt;T&gt;&amp; <var>rhs</var>);</code>
  </p>

  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_copy_constructible&lt;T&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>Constructs an <code>optional</code> object. If <code>bool(<var>rhs</var>) == true</code> initializes the contained value as if direct-non-list-initializing an object of type <code>T</code> with the expression <code>*<var>rhs</var></code>.</p></dd>
    <dt>Postconditions:</dt> <dd><p>If <code>bool(<var>rhs</var>) == false</code> then <code>bool(*this) == false</code>; otherwise <code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to <code>*<var>rhs</var></code>.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever the execution of <code>T</code>'s constructor selected for the copy throws.</p></dd>
  </dl>
  
  
  <p class="function">
  <code>optional&lt;T&gt;::optional(optional&lt;T&gt; &amp;&amp; <var>rhs</var>) noexcept(<em>see below</em>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_move_constructible&lt;T&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>Constructs an <code>optional</code> object. If <code>bool(<var>rhs</var>) == true</code> initializes the contained value as if direct-non-list-initializing an object of type <code>T</code> with the expression <code>std::move(*<var>rhs</var>)</code>.</p></dd>
    <dt>Postconditions:</dt> <dd><p>If initially <code>bool(<var>rhs</var>) == false</code> then <code>bool(*this) == false</code> and <code>bool(<var>rhs</var>) == false</code>; otherwise <code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to the value <code>*<var>rhs</var></code> had initially and <code>bool(<var>rhs</var>) == true</code>.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever the execution of <code>T</code>'s constructor selected for the copy throws.</p></dd>
    <dt>Remarks:</dt> <dd><p>The expression inside <code>noexcept</code> is equivalent to:</p> <pre>is_nothrow_move_constructible&lt;T&gt;::value</pre></dd>
  </dl>

  <p class="function">
  <code>optional&lt;T&gt;::optional(const T&amp; <var>v</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_copy_constructible&lt;T&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>Constructs an <code>optional</code> object by direct-non-list-initializing the contained value with the expression <code><var>v</var></code>.</p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to <code><var>v</var></code>.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever the execution of <code>T</code>'s constructor selected for the copy throws.</p></dd>
  </dl>
  
  
  <p class="function">
  <code>optional&lt;T&gt;::optional(T&amp;&amp; <var>v</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_move_constructible&lt;T&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>Constructs an <code>optional</code> object by direct-non-list-initializing the contained value with the expression <code>std::move(<var>v</var>)</code>.</p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to value that <code><var>v</var></code> had initially.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever the execution of <code>T</code>'s constructor selected for the move throws.</p></dd>
  </dl>
  
<!--  
  <p class="function">
  <code>template &lt;class U&gt; explicit optional&lt;T&gt;::optional(U&amp;&amp; <var>v</var>);<br>template &lt;class U&gt; optional&lt;T&gt;::optional(U&amp;&amp; <var>v</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_constructible&lt;T, U&amp;&amp;&gt;::value</code> is true.</p></dd>
    <dt>Effects:</dt> <dd><p>Constructs an engaged <code>optional</code> object; initializes the contained value as if constructing an object of type <code>T</code> with argument <code>std::forward&lt;U&gt;(<var>v</var>)</code>.</p></dd>

    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to <code><var>v</var></code> if converted to <code>T</code>.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever the execution of <code>T</code>'s constructor selected for the initialization throws.</p></dd>
    <dt>Remarks:</dt> <dd><p>The first function shall not participate in overload resolution unless <code>OnlyExplicitlyConstructible(T, U&amp;&amp;)</code> is <code>true</code>. The second function shall not participate in the overload resolution unless <code>is_convertible&lt;U&amp;&amp;, T&gt;::value</code> is <code>true</code>. The expression inside <code>noexcept</code> is equivalent to:</p> <pre>noexcept(T(std::declval&lt;U&amp;&amp;&gt;()))</pre></dd>
  </dl>
  
  
  <p class="function">
  <code>template &lt;class U&gt; explicit optional&lt;T&gt;::optional(const optional&lt;U&gt;&amp; <var>rhs</var>);<br>template &lt;class U&gt;  optional&lt;T&gt;::optional(const optional&lt;U&gt;&amp; <var>rhs</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_constructible&lt;T, const U&amp;&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>Constructs an <code>optional</code> object. If <code>bool(<var>rhs</var>) == true</code> initializes the contained value as if constructing an object of type <code>T</code> with argument <code>*<var>rhs</var></code></p></dd>
    <dt>Postconditions:</dt> <dd><p>If <code>bool(<var>rhs</var>) == false</code> then <code>bool(*this) == false</code>; otherwise <code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to <code>*<var>rhs</var></code> if converted to <code>T</code>.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever the execution of <code>T</code>'s constructor selected for the initialization throws.</p></dd>
    <dt>Remarks:</dt> <dd><p>The first function shall not participate in overload resolution unless <code>OnlyExplicitlyConstructible(T, const U&amp;)</code> is <code>true</code>. The second function shall not participate in the overload resolution unless <code>is_convertible&lt;const U&amp;, T&gt;::value</code> is <code>true</code>.</dd>
  </dl>
  
  
  <p class="function">
  <code>template &lt;class U&gt; explicit optional&lt;T&gt;::optional(optional&lt;U&gt;&amp;&amp; <var>rhs</var>);<br>template &lt;class U&gt;  optional&lt;T&gt;::optional(optional&lt;U&gt;&amp;&amp; <var>rhs</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_constructible&lt;T, U&amp;&amp;&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>Constructs an <code>optional</code> object. If <code>bool(<var>rhs</var>) == true</code> initializes the contained value as if constructing an object of type <code>T</code> with argument <code>std::move(*<var>rhs</var>)</code></p></dd>
    <dt>Throws:</dt> <dd><p>Whatever the execution of <code>T</code>'s constructor selected for the initialization throws.</p></dd>
    <dt>Remarks:</dt> <dd><p>The first function shall not participate in overload resolution unless <code>OnlyExplicitlyConstructible(T, U&amp;&amp;)</code> is <code>true</code>. The second function shall not participate in the overload resolution unless <code>is_convertible&lt;U&amp;&amp;, T&gt;::value</code> is <code>true</code>.</dd>
  </dl>
  
  <p class="function">
  <code>template &lt;class U&gt; explicit optional&lt;T&gt;::optional(initializer_list&lt;U&gt; <var>il</var>);<br>template &lt;class U&gt;  optional&lt;T&gt;::optional(initializer_list&lt;U&gt;<var>il</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_constructible&lt;T, initializer_list&lt;U&gt;&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>Constructs an <code>optional</code> object. If <code>bool(<var>rhs</var>) == true</code> initializes the contained value as if constructing an object of type <code>T</code> with argument <code><var>il</var></code></p></dd>
    <dt>Throws:</dt> <dd><p>Whatever the execution of <code>T</code>'s constructor selected for the initialization throws.</p></dd>
    <dt>Remarks:</dt> <dd><p>The first function shall not participate in overload resolution unless <code>OnlyExplicitlyConstructible(T, initializer_list&lt;U&gt;)</code> is <code>true</code>. The second function shall not participate in the overload resolution unless <code>is_convertible&lt;initializer_list&lt;U&gt;, T&gt;::value</code> is <code>true</code>.</dd>
  </dl>
-->
  
  <p class="function">
  <code>template &lt;class... Args&gt; explicit optional(emplace_t, Args&amp;&amp;... <var>args</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_constructible&lt;T, Args&amp;&amp;...&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>Constructs an engaged <code>optional</code> object. Initializes the contained value as if constructing an object of type T with the arguments <code>std::forward&lt;Args&gt;(<var>args</var>)...</code>.</p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true</code>.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever the execution of <code>T</code>'s constructor selected for the initialization throws.</p></dd>
  </dl>


  <p class="function">
  <code>template &lt;class U, class... Args&gt;<br>
  explicit optional(emplace_t, initializer_list&lt;U&gt; <var>il</var>, Args&amp;&amp;... <var>args</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_constructible&lt;T, initializer_list&lt;U&gt;, Args&amp;&amp;...&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>Constructs an engaged <code>optional</code> object. Initializes the contained value as if constructing an object of type T with the arguments <code><var>il</var>, std::forward&lt;Args&gt;(<var>args</var>)...</code>.</p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true</code>.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever the execution of <code>T</code>'s constructor selected for the initialization throws.</p></dd>
    <dt>Remarks:</dt> <dd><p>The function shall not participate in overload resolution unless <code>is_constructible&lt;T, initializer_list&lt;U&gt;, Args&amp;&amp;...&gt;::value</code> is <code>true</code>.</p></dd>
  </dl>


<h5><a name="optional.object.dtor">20.5.4.2 Destructor  <span style="float:right">[optional.object.dtor]</span></a></h5>
  
  <p class="function"> 
  <code>optional&lt;T&gt;::~optional();</code>
  </p>
  
  <dl class="attribute">
    <dt>Effects:</dt> <dd><p>If <code>bool(*this) == true</code>, calls <code><var>val</var>-&gt;T::~T()</code>. Destroys the <code>optional</code> object.</p></dd>
  </dl>
  
  
  
<h5><a name="optional.object.assign">20.5.4.3 Assignment  <span style="float:right">[optional.object.assign]</span></a></h5>
  
  
  <p class="function">
  <code>optional&lt;T&gt;&amp; optional&lt;T&gt;::operator=(nullopt_t) noexcept;</code>
  </p>

  <dl class="attribute">
    <dt>Effects:</dt> <dd><p>If <code>bool(*this) == true</code> calls <code><var>val</var>-&gt;T::~T()</code> to destroy the <em>contained value</em>; otherwise no effect.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code></p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == false</code>.</p></dd>
  </dl>
  
  <!--
  <p class="function">
  <code>optional&lt;T&gt;&amp; optional&lt;T&gt;::operator=(const T&amp; <var>rhs</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_copy_constructible&lt;T&gt;::value</code> is <code>true</code> and <code>is_copy_assignable&lt;T&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>If <code>bool(*this) == true</code> assigns <code><var>rhs</var></code> to the contained value; otherwise constructs the contained value as if direct-non-list-initializing object of type <code>T</code> with <code><var>rhs</var></code>.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code></p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to <code><var>rhs</var></code>.</p></dd>
    <dt>Exception Safety:</dt> <dd><p>If any exception is thrown value of <code><var>init</var></code> remains unchanged. If an exception is thrown during the call to <code>T</code>'s copy constructor, no effect. If an exception is thrown during the call to <code>T</code>'s copy assignment, the state of its contained value is as defined by the exception safety guarantee of <code>T</code>'s copy assignment.</p></dd>
  </dl>

  
  <p class="function">
  <code>optional&lt;T&gt;&amp; optional&lt;T&gt;::operator=(T&amp;&amp; <var>rhs</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_move_constructible&lt;T&gt;::value</code> is <code>true</code> and <code>is_move_assignable&lt;T&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>If <code>bool(*this) == true</code> assigns <code>std::move(<var>rhs</var>)</code> to the contained value; otherwise constructs the contained value as if direct-non-list-initializing object of type <code>T</code> with <code>std::move(<var>rhs</var>)</code>.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code></p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to the value that <code><var>rhs</var></code> had initially.</p></dd>
    <dt>Exception Safety:</dt> <dd><p>If any exception is thrown value of <code><var>init</var></code> remains unchanged. If an exception is thrown during the call to <code>T</code>'s move constructor, the state of <code><var>rhs</var></code> is determined by exception safety guarantee of <code>T</code>'s move constructor. If an exception is thrown during the call to <code>T</code>'s move assignment, the state of <code><var>*val</var></code> and <code><var>rhs</var></code> is determined by exception safety guarantee of <code>T</code>'s move assignment.</p></dd>
  </dl>
  
  -->
  <p class="function">
  <code>optional&lt;T&gt;&amp; optional&lt;T&gt;::operator=(const optional&lt;T&gt;&amp; <var>rhs</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_copy_constructible&lt;T&gt;::value</code> is <code>true</code> and <code>is_copy_assignable&lt;T&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>If <code><var>init</var> == false &amp;&amp; <var>rhs.init</var> == false</code>, no effect. If <code><var>init</var> == true && <var>rhs.init</var> == false</code>, destroys the contained value by calling <code><var>val</var>-&gt;T::~T()</code>. If <code><var>init</var> == false &amp;&amp; <var>rhs.init</var> == true</code>, constructs the contained value as if direct-non-list-initializing an object of type <code>T</code> with <code>*<var>rhs</var></code>. If <code><var>init</var> == true &amp;&amp; <var>rhs.init</var> == true</code>, assigns <code>*<var>rhs</var></code> to the contained value.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code></p></dd>
    <dt>Postconditions:</dt> <dd><p>If <code>bool(<var>rhs</var>) == false</code> then <code>bool(*this) == false</code>; otherwise <code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to <code>*<var>rhs</var></code>.</p></dd>
    <dt>Exception Safety:</dt> <dd><p>If any exception is thrown values of <code><var>init</var></code> and <code><var>rhs.init</var></code> remain unchanged. If an exception is thrown during the call to <code>T</code>'s copy constructor, no effect. If an exception is thrown during the call to <code>T</code>'s copy assignment, the state of its contained value is as defined by the exception safety guarantee of <code>T</code>'s copy constructor.</p></dd>
  </dl>
  
 
  <p class="function">
  <code>optional&lt;T&gt;&amp; optional&lt;T&gt;::operator=(optional&lt;T&gt;&amp;&amp; <var>rhs</var>) noexcept(<em>see below</em>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_move_constructible&lt;T&gt;::value</code> is <code>true</code> and <code>is_move_assignable&lt;T&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>If <code><var>init</var> == false &amp;&amp; <var>rhs.init</var> == false</code>, no effect. If <code><var>init</var> == true && <var>rhs.init</var> == false</code>, destroys the contained value by calling <code><var>val</var>-&gt;T::~T()</code>. If <code><var>init</var> == false &amp;&amp; <var>rhs.init</var> == true</code>, constructs the contained value as if direct-non-list-initializing an object of type <code>T</code> with <code>std::move(*<var>rhs</var>)</code>. If <code><var>init</var> == true &amp;&amp; <var>rhs.init</var> == true</code>, assigns <code>std::move(*<var>rhs</var>)</code> to the contained value.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code></p></dd>
    <dt>Postconditions:</dt> <dd><p><p>If initially <code>bool(<var>rhs</var>) == false</code> then <code>bool(*this) == false</code> and <code>bool(<var>rhs</var>) == false</code>; otherwise <code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to the value that <code>*<var>rhs</var></code> had initially and <code>bool(<var>rhs</var>) == true</code>.</p></dd>

    <dt>Remarks:</dt> <dd><p>The expression inside <code>noexcept</code> is equivalent to:</p> <pre>is_nothrow_move_assignable&lt;T&gt;::value && is_nothrow_move_constructible&lt;T&gt;::value</pre></dd>
    <dt>Exception Safety:</dt> <dd><p>If any exception is thrown values of <code><var>init</var></code> and <code><var>rhs.init</var></code> remain unchanged. If an exception is thrown during the call to <code>T</code>'s move constructor, the state of <code>*rhs.val</code> is determined by exception safety guarantee of <code>T</code>'s move constructor. If an exception is thrown during the call to <code>T</code>'s move assignment, the state of <code><var>*val</var></code> and <code>*rhs.val</code> is determined by exception safety guarantee of <code>T</code>'s move assignment.</p></dd>

  </dl>
  
  
  <p class="function">
  <code>template &lt;class U&gt; optional&lt;T&gt;&amp; optional&lt;T&gt;::operator=(U&amp;&amp; <var>v</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_constructible&lt;T, U&gt;::value</code> is <code>true</code> and <code>is_assignable&lt;U, T&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>If <code>bool(*this) == true</code> assigns <code>std::forward&lt;U&gt;(<var>v</var>)</code> to the contained value; otherwise constructs the contained value as if direct-non-list-initializing object of type <code>T</code> with <code>std::forward&lt;U&gt;(<var>v</var>)</code>.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code></p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to the value that <code><var>v</var></code> had initially.</p></dd>
    <dt>Exception Safety:</dt> <dd><p>If any exception is thrown value of <code><var>init</var></code> remains unchanged. If an exception is thrown during the call to <code>T</code>'s constructor, the state of <code><var>v</var></code> is determined by exception safety guarantee of <code>T</code>'s constructor. If an exception is thrown during the call to <code>T</code>'s assignment, the state of <code><var>*val</var></code> and <code><var>v</var></code> is determined by exception safety guarantee of <code>T</code>'s assignment.</p></dd>
    <dt>Remarks:</dt> <dd><p>The function shall not participate in overload resolution unless  <code>is_same&lt;typename remove_reference&lt;U&gt;::type, T&gt;::value</code> is  <code>true</code>.</dd>
  </dl>
  <p>[<i>Note:</i> The reson to provide such genereic assignment and then constraining it so that effectively <code>T</code> == <code>U</code> is to guarantee that assignment of the form <code>o = {}</code> is unambiguous. &mdash;<i>end note</i>]</p>

  <!--
  <p class="function">
  <code>template &lt;class U&gt; optional&lt;T&gt;&amp; optional&lt;T&gt;::operator=(U&amp;&amp; <var>v</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_constructible&lt;T, U&gt;::value</code> is <code>true</code> and <code>is_assignable&lt;U, T&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>If <code>bool(*this) == true</code> assigns <code>std::forward&lt;U&gt;(<var>v</var>)</code> to the contained value; otherwise constructs the contained value as if direct-non-list-initializing object of type <code>T</code> with <code>std::forward&lt;U&gt;(<var>v</var>)</code>.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code></p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to the value that <code><var>v</var></code> had initially.</p></dd>
    <dt>Exception Safety:</dt> <dd><p>If any exception is thrown value of <code><var>init</var></code> remains unchanged. If an exception is thrown during the call to <code>T</code>'s constructor, the state of <code><var>v</var></code> is determined by exception safety guarantee of <code>T</code>'s constructor. If an exception is thrown during the call to <code>T</code>'s assignment, the state of <code><var>*val</var></code> and <code><var>v</var></code> is determined by exception safety guarantee of <code>T</code>'s assignment.</p></dd>
    <dt>Remarks:</dt> <dd><p>The function shall not participate in overload resolution if type <code>decay&lt;U&gt;::type</code> is an instantiation of class template <code>optional</code>.</dd>
  </dl>
  
  
  <p class="function">
  <code>template &lt;class U&gt; optional&lt;T&gt;&amp; optional&lt;T&gt;::operator=(const optional&lt;U&gt;&amp; <var>rhs</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_constructible&lt;T, const U&amp;&gt;::value</code> is <code>true</code> and <code>is_assignable&lt;T, const U&amp;&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>If <code><var>init</var> == false &amp;&amp; <var>rhs.init</var> == false</code>, no effect. If <code><var>init</var> == true && <var>rhs.init</var> == false</code>, destroys the contained value by calling <code><var>val</var>-&gt;T::~T()</code>. If <code><var>init</var> == false &amp;&amp; <var>rhs.init</var> == true</code>, constructs the contained value as if direct-non-list-initializing an object of type <code>T</code> with <code>*<var>rhs</var></code>. If <code><var>init</var> == true &amp;&amp; <var>rhs.init</var> == true</code>, assigns <code>*<var>rhs</var></code> to the contained value.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code></p></dd>
    <dt>Postconditions:</dt> <dd><p>If <code>bool(<var>rhs</var>) == false</code> then <code>bool(*this) == false</code>; otherwise <code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to <code>*<var>rhs</var></code> converted to <code>T</code>.</p></dd>
    <dt>Exception Safety:</dt> <dd><p>If any exception is thrown values of <code><var>init</var></code> and <code><var>rhs.init</var></code> remain unchanged. If an exception is thrown during the call to <code>T</code>'s constructor, no effect. If an exception is thrown during the call to <code>T</code>'s  assignment, the state of i<code><var>*val</var></code> is defined by the exception safety guarantee of <code>T</code>'s  assignment.</p></dd>
  </dl>
  
  
  <p class="function">
  <code>template &lt;class U&gt; optional&lt;T&gt;&amp; optional&lt;T&gt;::operator=(optional&lt;U&gt;&amp;&amp; <var>rhs</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_constructible&lt;T, U&amp;&amp;&gt;::value</code> is <code>true</code> and <code>is_assignable&lt;T, U&amp;&amp;&gt;::value</code> is <code>true</code>.</p></dd>

    <dt>Effects:</dt> <dd><p>If <code><var>init</var> == false &amp;&amp; <var>rhs.init</var> == false</code>, no effect. If <code><var>init</var> == true && <var>rhs.init</var> == false</code>, destroys the contained value by calling <code><var>val</var>-&gt;T::~T()</code>. If <code><var>init</var> == false &amp;&amp; <var>rhs.init</var> == true</code>, constructs the contained value as if direct-non-list-initializing an object of type <code>T</code> with <code>std::move(*<var>rhs</var>)</code>. If <code><var>init</var> == true &amp;&amp; <var>rhs.init</var> == true</code>, assigns <code>std::move(*<var>rhs</var>)</code> to the contained value.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code></p></dd>
    <dt>Postconditions:</dt> <dd><p>If <code>bool(<var>rhs</var>) == false</code> then <code>bool(*this) == false</code>; otherwise <code>bool(*this) == true</code> and <code>*(*this)</code> is equivalent to the value <code>*<var>rhs</var></code> had initially if converted to <code>T</code>.</p></dd>
    <dt>Exception Safety:</dt> <dd><p>If any exception is thrown values of <code><var>init</var></code> and <code><var>rhs.init</var></code> remain unchanged. If an exception is thrown during the call to <code>T</code>'s constructor, no effect. If an exception is thrown during the call to <code>T</code>'s assignment, the state of <code><var>*val</var></code> is defined by the exception safety guarantee of <code>T</code>'s assignment.</p></dd>
  </dl>
  

  <p class="function">
  <code>template &lt;class U&gt; optional&lt;T&gt;&amp; optional&lt;T&gt;::operator=(initializer_list&lt;U&gt; <var>il</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_constructible&lt;T, initializer_list&lt;U&gt;&gt;::value</code> is <code>true</code> and <code>is_assignable&lt;T, initializer_list&lt;U&gt;&gt;::value</code> is <code>true</code>.</p></dd>
     <dt>Effects:</dt> <dd><p>If <code>bool(*this) == true</code> assigns <code><var>il</var></code> to the contained value; otherwise constructs the contained value as if direct-non-list-initializing object of type <code>T</code> with <code><var>il</var></code>.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code></p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true</code>.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever <code>T::T(initializer_list&lt;U&gt;)</code> or <code>T::operator=(initializer_list&lt;U&gt;)</code> throws.</p></dd>
    <dt>Exception Safety:</dt> <dd><p>If any exception is thrown, value of <code><var>init</var></code> remains unchanged. If an exception is thrown during the call to <code>T</code>'s constructor, no effect. If an exception is thrown during the call to <code>T</code>'s assignment, the state of its contained value is as defined by the exception safety guarantee of <code>T</code>'s assignemnt.</p></dd>
    <dt>Remarks:</dt> <dd><p>The function shall not participate in overload resolution unless <code>is_constructible&lt;T, initializer_list&lt;U&gt;&gt;::value</code> is <code>true</code> and <code>is_assignable&lt;T, initializer_list&lt;U&gt;&gt;::value</code> is <code>true</code>.</dd>
  </dl>
-->
  
  <p class="function">
  <code>template &lt;class... Args&gt; optional&lt;T&gt;&amp; optional&lt;T&gt;::emplace(Args&amp;&amp;... <var>args</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_constructible&lt;T, Args&amp;&amp;...&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>Calls <code>*this = nullopt</code>. Then initializes the contained value as if constructing an object of type <code>T</code> with the arguments <code>std::forward&lt;Args&gt;(<var>args</var>)...</code>.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code></p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true</code>.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever expression <code>T(std::forward&lt;Args&gt;(<var>args</var>)...)</code> throws.</p></dd>
    <dt>Exception Safety:</dt> <dd><p>If an exception is thrown during the call to <code>T</code>'s constructor, <code>*this</code> is disengaged, and the previous <code><var>*val</var></code> (if any) has been destroyed.</p></dd>
  </dl>
  
  
   <p class="function">
  <code>template &lt;class U, class... Args&gt; optional&lt;T&gt;&amp; optional&lt;T&gt;::emplace(initializer_list&lt;U&gt; <var>il</var>, Args&amp;&amp;... <var>args</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_constructible&lt;T, initializer_list&lt;U&gt;, Args&amp;&amp;...&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>Calls <code>*this = nullopt</code>. Then initializes the contained value as if constructing an object of type <code>T</code> with the arguments <code><var>il</var>, std::forward&lt;Args&gt;(<var>args</var>)...</code>.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code></p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true</code>.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever expression <code>T(<var>il</var>, std::forward&lt;Args&gt;(<var>args</var>)...)</code> throws.</p></dd>
    <dt>Exception Safety:</dt> <dd><p>If an exception is thrown during the call to <code>T</code>'s constructor, <code>*this</code> is disengaged, and the previous <code><var>*val</var></code> (if any) has been destroyed.</p></dd>
    <dt>Remarks:</dt> <dd><p>The function shall not participate in overload resolution unless <code>is_constructible&lt;T, initializer_list&lt;U&gt;, Args&amp;&amp;...&gt;::value</code> is <code>true</code>.</p></dd>
  </dl>


  
<h5><a name="optional.object.swap">20.5.4.4 Swap <span style="float:right">[optional.object.swap]</span></a></h5>


  <p class="function">
  <code>void optional&lt;T&gt;::swap(optional&lt;T&gt;& rhs) noexcept(<em>see below</em>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>T</code> shall be swappable for lvalues and <code>is_move_constructible&lt;T&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>If <code><var>init</var> == false && <var>rhs.init</var> == false</code>, no effect. If <code><var>init</var> == true && <var>rhs.init</var> == false</code>, constructs the contained value of <code><var>rhs</var></code> by direct-initialization with <code>std::move(*(*this))</code>, followed by <code>val-&gt;T::~T(), swap(<var>init</var>, <var>rhs.init</var>)</code>. If <code><var>init</var> == false && <var>rhs.init</var> == true</code>, constructs the contained value of <code>*this</code> by direct-initialization with <code>std::move(*<var>rhs</var>)</code>, followed by <code>rhs.val-&gt;T::~T(), swap(<var>init</var>, <var>rhs.init</var>)</code>. If <code><var>init</var> == true && <var>rhs.init</var> == true</code>, calls <code>swap(*(*this), *<var>rhs</var>)</code>.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever expressions <code>swap(declval&lt;T&amp;&gt;(), declval&lt;T&amp;&gt;())</code> and <code>T{move(declval&lt;T&amp;&amp;&gt;())}</code> throw.</p></dd>
    <dt>Remarks:</dt> <dd><p>The expression inside <code>noexcept</code> is equivalent to: <pre>is_nothrow_move_constructible&lt;T&gt;::value && noexcept(swap(declval&lt;T&amp;&gt;(), declval&lt;T&amp;&gt;()))</pre></dd>
    <dt>Exception Safety:</dt> <dd><p>If any exception is thrown values of <code><var>init</var></code> and <code><var>rhs.init</var></code> remain unchanged. If an exception is thrown during the call to function <code>swap</code> the state of <code><var>*val</var></code> and <code>*rhs.val</code> is determined by the exception safety quarantee of <code>swap</code> for lvalues of <code>T</code>. If an exception is thrown durning the call to <code>T</code>'s move constructor, the state of <code><var>*val</var></code> and <code>*rhs.val</code> is determined by the exception safety quarantee of <code>T</code>'s move constructor.</p></dd>

  </dl>

  
  
<h5><a name="optional.object.observe">20.5.4.5 Observers  <span style="float:right">[optional.object.observe]</span></a></h5>


  <p class="function">
  <code>T const* optional&lt;T&gt;::operator-&gt;() const;<br>T* optional&lt;T&gt;::operator-&gt;();</code>

  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>bool(*this) == true</code>.</p></dd>
    <dt>Returns:</dt> <dd><p><code>val</code></p></dd>
    <dt>Throws:</dt> <dd><p>nothing.</p></dd>
  </dl>
  
  
  <p class="function">
  <code>T const&amp; optional&lt;T&gt;::operator*() const;<br>T&amp;       optional&lt;T&gt;::operator*();</code>

  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>bool(*this) == true</code>.</p></dd>
    <dt>Returns:</dt> <dd><p><code><var>*val</var></code></p></dd>
    <dt>Throws:</dt> <dd><p>nothing.</p></dd>

  </dl>
  
  
  <p class="function">
  <code>explicit optional&lt;T&gt;::operator bool() noexcept;</code>
  </p>
  
  <dl class="attribute">
    <dt>Returns:</dt> <dd><p><code><var>init</var></code></p></dd>

  </dl>
  
  <!--
  <p class="function">
  <code>T optional&lt;T&gt;::get_value_or(const T&amp; def) const&amp; noexcept(<em>see below</em>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>T</code> shall meet the <code>CopyConstructible</code> requirements.</p></dd>
    <dt>Returns:</dt> <dd><p>If <code><var>init</var> == true</code>, <code><var>*val</var></code>; otherwise <code><var>def</var></code>.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever <code>T</code>'s copy-constructor throws.</p></dd>
    <dt>Remarks:</dt> <dd><p>The expression inside <code>noexcept</code> is equivalent to: <pre>is_nothrow_copy_constructible&lt;T&gt;::value</pre></dd>
  </dl>
  
  
  <p class="function">
  <code>T optional&lt;T&gt;::get_value_or(T&amp;&amp; def) &amp;&amp; noexcept(<em>see below</em>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>T</code> shall meet the <code>MoveConstructible</code> requirements.</p></dd>
    <dt>Returns:</dt> <dd><p>If <code><var>init</var> == true</code>, <code>move(*val)</code>; otherwise <code>move(def)</code>.</p></dd>
    <dt>Throws:</dt> <dd><p>Whatever <code>T</code>'s move-constructor throws.</p></dd>
    <dt>Remarks:</dt> <dd><p>The expression inside <code>noexcept</code> is equivalent to: <pre>is_nothrow_move_constructible&lt;T&gt;::value</pre></dd>
    <dt>Exception Safety:</dt> <dd><p>If an exception is thrown durning the call to <code>T</code>'s move constructor, the value of <code><var>init</var></code> remain unchanged and the state of <code><var>*val</var></code> and <code><var>def</var></code> is determined by the exception safety quarantee of <code>T</code>'s move constructor. </p></dd>
  </dl>
  
  
  <p class="function">
  <code>T&amp; optional&lt;T&gt;::get_value_or(T&amp; <var>def</var>) &amp; noexcept;</code>
  </p>
  
  <dl class="attribute">
    <dt>Returns:</dt> <dd><p>If <code><var>init</var> == true</code>, <code><var>*val</var></code>; otherwise <code><var>def</var></code>.</p></dd>
  </dl>
  -->
  
  
<h4><a name="optional.lref">20.5.5 <code>optional</code> for lvalue reference types <span style="float:right">[optional.lref]</span></a></h4>


<pre>
namespace std {
namespace experimental {

  template &lt;class T&gt;
  class optional&lt;T&amp;&gt;
  {
  public:
    typedef T&amp; value_type;

    // <em><a href="#optional.lref.ctor">20.5.5.1</a>, construction/destruction</em>
    constexpr optional() noexcept;
    constexpr optional(nullopt_t) noexcept;
    optional(T&amp;) noexcept;
    optional(T&amp;&amp;) = delete;
    optional(const optional&amp;) noexcept;
    template &lt;class U&gt; optional(const optional&lt;U&amp;&gt;&amp;) noexcept;
    explicit optional(emplace_t, T&amp;) noexcept;
    explicit optional(emplace_t, T&amp;&amp;) = delete;
    ~optional() = default;

    // <em><a href="#optional.lref.mutate">20.5.5.2</a>, mutation</em>
    optional&amp; operator=(nullopt_t) noexcept;
    optional&amp; operator=(optional&amp;&amp;) = delete;
    optional&amp; operator=(const optional&amp;) = delete;
    optional&amp; emplace(T&amp;) noexcept;
    optional&amp; emplace(T&amp;&amp;) = delete;

    // <em><a href="#optional.lref.observe">20.5.5.3</a>, observers</em>
    T* operator-&gt;() const;
    T&amp; operator*() const;
    explicit operator bool() const noexcept;

  <var>private:</var>
    <var>T* ref;  //</var> <em>exposition only</em>
  };

} <em>// namespace experimental</em>
} <em>// namespace std</em>
</pre>

  <p>Engaged instances of <code>optional&lt;T&gt;</code> where <code>T</code> is of lvalue reference type, refer to objects of type <code>std::remove_reference&lt;T&gt;::type</code>, but their life-time is not connected to the life-time of the referred to object. Destroying or disengageing the optional object does not affect the state of the referred to object.</p>
  
  <p>Member <code><var>ref</var></code> is provided for exposition only. Implementations need not provide this member. If <code><var>ref</var> == nullptr</code>, optional object is disengaged; otherwise <code><var>ref</var></code> points to a valid object.
  </p>

 
 
<h5><a name="optional.lref.ctor">20.5.5.1 Construction and destruction <span style="float:right">[optional.lref.ctor]</span></a></h5>


  <p class="function">
  <code>constexpr optional&lt;T&amp;&gt;::optional() noexcept;</code><br>
  <code>constexpr optional&lt;T&amp;&gt;::optional(nullopt_t) noexcept;</code>

  </p>

  <dl class="attribute">
    <dt>Effects:</dt> <dd><p>Constructs a disengaged <code>optional</code> object by initializing <code><var>ref</var></code> with <code>nullptr</code>.</p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == false</code>.</p></dd>
    <dt>Remarks:</dt> <dd><p>For every object type <code>T</code> these constructors shall be <code>constexpr</code> constructors (7.1.5).</p></dd>
  </dl>

  <p class="function">
  <code>optional&lt;T&amp;&gt;::optional(T&amp; <var>v</var>) noexcept;</code>
  </p>
  
  <dl class="attribute">
    <dt>Effects:</dt> <dd><p>Constructs an engaged <code>optional</code> object by initializing <code><var>ref</var></code> with <code>addressof(<var>v</var>)</code>.</p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true &amp;&amp; addressof(*(*this)) == addressof(<var>v</var>)</code>.</p></dd>
  </dl> 
  
  
  <p class="function">
  <code>optional&lt;T&amp;&gt;::optional(const optional&amp; <var>rhs</var>) noexcept;<br>template &lt;class U&gt; optional&lt;T&amp;&gt;::optional(const optional&lt;U&amp;&gt;&amp; <var>rhs</var>) noexcept;</code>
  </p>

  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_base_of&lt;T, U&gt;::value == true</code>, and <code>is_convertible&lt;U&amp;, T&amp;&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>If <code><var>rhs</var></code> is disengaged, initializes <code><var>ref</var></code> with <code>nullptr</code>; otherwise, constructs an engaged object by initializing <code><var>ref</var></code> with <code>addressof(*<var>rhs</var>)</code>.</p></dd>
    <dt>Postconditions:</dt> <dd><p>If <code>bool(<var>rhs</var>) == true</code>, then <code>bool(*this) == true &amp;&amp; addressof(*(*this)) == addressof(*<var>rhs</var>)</code>; otherwise <code>bool(*this) == false</code>.</p></dd>
  </dl>   
  
  <p class="function">
  <code>explicit optional&lt;T&amp;&gt;::optional(emplace_t, T&amp; <var>v</var>) noexcept;</code>
  </p>
  
  <dl class="attribute">
    <dt>Effects:</dt> <dd><p>Constructs an engaged <code>optional</code> object by initializing <code><var>ref</var></code> with <code>addressof(<var>v</var>)</code>.</p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true &amp;&amp; addressof(*(*this)) == addressof(<var>v</var>)</code>.</p></dd>
  </dl> 
  
  
  <p class="function">
  <code>optional&lt;T&amp;&gt;::~optional() = default;</code>
  </p>
  
  <dl class="attribute">
    <dt>Effects:</dt> <dd><p>No effect. This destructor shall be a trivial destructor.</p></dd>
  </dl>  
  
  
<h5><a name="optional.lref.mutate">20.5.5.2 Mutation <span style="float:right">[optional.lref.mutate]</span></a></h5>
  
  
  <p class="function">
  <code>optional&lt;T&amp;&gt;&amp; optional&lt;T&amp;&gt;::operator=(nullopt_t) noexcept;</code>
  </p>

  <dl class="attribute">
    <dt>Effects:</dt> <dd><p>Assigns <code><var>ref</var></code> with a value of <code>nullptr</code>. If <code><var>ref</var></code> was non-null initially, the object it referred to is unaffected.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code>.</p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == false</code>.</p></dd>
  </dl>
  
  
  <p class="function">
  <code>optional&lt;T&amp;&gt;&amp; optional&lt;T&amp;&gt;::emplace(T&amp; <var>v</var>) noexcept;</code>
  </p>

  <dl class="attribute">
    <dt>Effects:</dt> <dd><p>Assigns <code><var>ref</var></code> with a value of <code>addressof(<var>v</var>)</code>. If <code><var>ref</var></code> was non-null initially, the object it referred to is unaffected.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*this</code>.</p></dd>
    <dt>Postconditions:</dt> <dd><p><code>bool(*this) == true &amp;&amp; addressof(*(*this)) == addressof(<var>v</var>)</code>.</p></dd>
	<dt>Remarks:</dt> <dd><p>If <code>*this</code> was engaged before the call the object it referred to is not affected.</p></dd>
  </dl>
  
  
<h5><a name="optional.lref.observe">20.5.5.3 Observers <span style="float:right">[optional.lref.observe]</span></a></h5>
  
  
  <p class="function">
  <code>T* optional&lt;T&amp;&gt;::operator-&gt;() const;</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>bool(*this) == true</code>.</p></dd>
    <dt>Returns:</dt> <dd><p><code><var>ref</var></code>.</p></dd>
    <dt>Throws:</dt> <dd><p>nothing.</p></dd>
  </dl>
  
  
  <p class="function">
  <code>T&amp; optional&lt;T&amp;&gt;::operator*() const;</code>
  </p>
  
  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>bool(*this) == true</code>.</p></dd>
    <dt>Returns:</dt> <dd><p><code>*<var>ref</var></code></p></dd>
    <dt>Throws:</dt> <dd><p>nothing.</p></dd>
  </dl>

  
  <p class="function">
  <code>explicit optional&lt;T&amp;&gt;::operator bool() noexcept;</code>
  </p>
  
  <dl class="attribute">
    <dt>Returns:</dt> <dd><p><code><var>ref</var> != nullptr</code></p></dd>
  </dl>  
  
  
  
<h4><a name="optional.inplace">20.5.6 In-place construction  <span style="float:right">[optional.inplace]</span></a></h4>


  <p class="function">
  <code>struct emplace_t{}; <br>constexpr emplace_t emplace{};</code>
  </p>

  <p>The struct <code>emplace_t</code> is a disengaged structure type used as a unique type to disambiguate constructor and function overloading. Specifically, <code>optional&lt;T&gt;</code> has a constructor with <code>emplace_t</code> as the first argument followed by an argument pack; this indicates that <code>T</code> should be constructed in-place (as if by a call to placement new expression) with forwarded argument pack as parameters.
  </p>

  
<h4><a name="optional.nullopt">20.5.7 Disengaged state indicator  <span style="float:right">[optional.nullopt]</span></a></h4>


  <p class="function">
  <code>struct nullopt_t{<em>see below</em>}; <br>constexpr nullopt_t nullopt(<em>unspecified</em>);</code>
  </p>

  <p>The struct <code>nullopt_t</code> is an empty structure type used as a unique type to indicate a disengaged state for <code>optional</code> objects. In particular, <code>optional&lt;T&gt;</code> has a constructor with <code>nullopt_t</code> as single argument; this indicates that a disengaged optional object shall be constructed.
  </p>
  
  <p>Type <code>nullopt_t</code> shall not have a default constructor. It shall be a literal type. Constant <code>nullopt</code> shall be initialized with argument of literal type.</p>
  
  
  
<h4><a name="optional.relops">20.5.8 Relational operators  <span style="float:right">[optional.relops]</span></a></h4>
 

  <p class="function"> 
  <code>template &lt;class T&gt; bool operator==(const optional&lt;T&gt;&amp; x, const optional&lt;T&gt;&amp; y);</code>
  </p>
  
  <dl class="attribute">
  <dt>Requires:</dt> <dd><p><code>T</code> shall meet the requirements of <code>EqualityComparable</code>.</p></dd>
  <dt>Returns:</dt> <dd><p>If <code>bool(x) != bool(y)</code>, <code>false</code>; otherwise if <code>bool(x) == false</code>, <code>true</code>; otherwise <code>*x == *y</code>.</p></dd>
  </dl>
  
  
  <p class="function">
  <code>template &lt;class T&gt; bool operator!=(const optional&lt;T&gt;&amp; x, const optional&lt;T&gt;&amp; y);</code>
  </p>
  
  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>!(x == y)</code>.</p></dd>
  </dl>
  
  
  <p class="function">
  <code>template &lt;class T&gt; bool operator&lt;(const optional&lt;T&gt;&amp; x, const optional&lt;T&gt;&amp; y);</code> 
  </p>

  <dl class="attribute">
  <dt>Requires:</dt> <dd><p><code>T</code> shall meet the requirements of <code>LessThanComparable</code>.</p></dd>
  <dt>Returns:</dt> <dd><p>If <code>(!y)</code>, <code>false</code>; otherwise, if <code>(!x)</code>, <code>true</code>; otherwise <code>*x &lt; *y</code>.</p></dd>
  </dl>

  
  <p class="function">
  <code>template &lt;class T&gt; bool operator&gt;(const optional&lt;T&gt;&amp; x, const optional&lt;T&gt;&amp; y);</code> 
  </p>

  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>(y < x)</code>.</p></dd>
  </dl>
  
 
  <p class="function"> 
  <code>template &lt;class T&gt; bool operator&lt;=(const optional&lt;T&gt;&amp; x, const optional&lt;T&gt;&amp; y);</code> 
  </p>

  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>!(y < x)</code>.</p></dd>
  </dl>
  
  
  <p class="function">
  <code>template &lt;class T&gt; bool operator&gt;=(const optional&lt;T&gt;&amp; x, const optional&lt;T&gt;&amp; y);</code> 
  </p>

  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>!(x < y)</code>.</p></dd>
  </dl>
 

 
<h4><a name="optional.nullops">20.5.9 Comparison with <code>nullopt</code> <span style="float:right">[optional.nullops]</span></a></h4>
 
  
  <p class="function">
  <code>template &lt;class T&gt; bool operator==(const optional&lt;T&gt;&amp; <var>x</var>, nullopt_t) noexcept;<br>template &lt;class T&gt; bool operator==(nullopt_t, const optional&lt;T&gt;&amp; x) noexcept;</code>
  </p>
  
  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>(!<var>x</var>)</code>.</p></dd>
  </dl>


  <p class="function">
  <code>template &lt;class T&gt; bool operator!=(const optional&lt;T&gt;&amp; <var>x</var>, nullopt_t) noexcept;<br>template &lt;class T&gt; bool operator!=(nullopt_t, const optional&lt;T&gt;&amp; x) noexcept;</code>
  </p>

  
  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>bool(<var>x</var>)</code>.</p></dd>
  </dl> 


  <p class="function">
  <code>template &lt;class T&gt; bool operator&lt;(const optional&lt;T&gt;&amp; <var>x</var>, nullopt_t) noexcept;</code>
  </p>
  
  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>false</code>.</p></dd>
  </dl>

  <p class="function">
  <code>template &lt;class T&gt; bool operator&lt;(nullopt_t, const optional&lt;T&gt;&amp; <var>x</var>) noexcept;</code>
  </p>
  
  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>bool(<var>x</var>)</code>.</p></dd>
  </dl>

  
  <p class="function">
  <code>template &lt;class T&gt; bool operator&lt;=(const optional&lt;T&gt;&amp; <var>x</var>, nullopt_t) noexcept;</code>
  </p>
  
  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>(!<var>x</var>)</code>.</p></dd>
  </dl>

  <p class="function">
  <code>template &lt;class T&gt; bool operator&lt;=(nullopt_t, const optional&lt;T&gt;&amp; <var>x</var>) noexcept;</code>
  </p>
  
  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>true</code>.</p></dd>
  </dl>
  
  
  <p class="function">
  <code>template &lt;class T&gt; bool operator&gt;(const optional&lt;T&gt;&amp; <var>x</var>, nullopt_t) noexcept;</code>
  </p>
  
  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>bool(<var>x</var>)</code>.</p></dd>
  </dl>

  <p class="function">
  <code>template &lt;class T&gt; bool operator&gt;(nullopt_t, const optional&lt;T&gt;&amp; <var>x</var>) noexcept;</code>
  </p>
  
  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>false</code>.</p></dd>
  </dl>

  
  <p class="function">
  <code>template &lt;class T&gt; bool operator&gt;=(const optional&lt;T&gt;&amp; <var>x</var>, nullopt_t) noexcept;</code>
  </p>
  
  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>true</code>.</p></dd>
  </dl>

  <p class="function">
  <code>template &lt;class T&gt; bool operator&gt;=(nullopt_t, const optional&lt;T&gt;&amp; <var>x</var>) noexcept;</code>
  </p>
  
  <dl class="attribute">
  <dt>Returns:</dt> <dd><p><code>(!<var>x</var>)</code>.</p></dd>
  </dl>
 

 
<h4><a name="optional.poisoned_comp">20.5.10 Poisoned comparison with <code>T</code> <span style="float:right">[optional.poisoned_comp]</span></a></h4>


  <p class="function">
  <code>template &lt;class T&gt; bool operator==(const optional&lt;T&gt;&amp;, const T&amp;) noexcept;<br>
  template &lt;class T&gt; bool operator==(const T&amp;, const optional&lt;T&gt;&amp;) noexcept;<br>
  template &lt;class T&gt; bool operator!=(const optional&lt;T&gt;&amp;, const T&amp;) noexcept;<br>
  template &lt;class T&gt; bool operator!=(const T&amp;, const optional&lt;T&gt;&amp;) noexcept;<br>
  template &lt;class T&gt; bool operator&lt;(const optional&lt;T&gt;&amp;, const T&amp;) noexcept;<br>
  template &lt;class T&gt; bool operator&lt;(const T&amp;, const optional&lt;T&gt;&amp;) noexcept;<br>
  template &lt;class T&gt; bool operator&lt;=(const optional&lt;T&gt;&amp;, const T&amp;) noexcept;<br>
  template &lt;class T&gt; bool operator&lt;=(const T&amp;, const optional&lt;T&gt;&amp;) noexcept;<br>
  template &lt;class T&gt; bool operator&gt;(const optional&lt;T&gt;&amp;, const T&amp;) noexcept;<br>
  template &lt;class T&gt; bool operator&gt;(const T&amp;, const optional&lt;T&gt;&amp;) noexcept;<br>
  template &lt;class T&gt; bool operator&gt;=(const optional&lt;T&gt;&amp;, const T&amp;) noexcept;<br>
  template &lt;class T&gt; bool operator&gt;=(const T&amp;, const optional&lt;T&gt;&amp;) noexcept;</code>
  </p>
 
 <dl class="attribute">
  <dt>Remarks:</dt> <dd><p>Program that causes the instantiation of one of the above templates is ill-formed.</p></dd>
  </dl>
  
 
<h4><a name="optional.specalg">20.5.11 Specialized algorithms <span style="float:right">[optional.specalg]</span></a></h4>


  <p class="function">
  <code>template &lt;class T&gt; void swap(optional&lt;T&gt;&amp; x, optional&lt;T&gt;&amp; y) noexcept(noexcept(x.swap(y)));</code>
  </p>

  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_reference&lt;T&gt;::value == false</code>.</p></dd>
    <dt>Effects:</dt> <dd><p>calls <code>x.swap(y)</code>.</p>  
  </dl>


  <p class="function">
  <code>template &lt;class T, class V&gt;<br>
    &nbsp;&nbsp;typename decay&lt;T&gt;::type get_value_or(const optional&lt;T&gt;&amp; <var>op</var>, V&amp;&amp; <var>v</var>);</code>
  </p>

  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_copy_constructible&lt;T&gt;::value</code> is <code>true</code> and <code>is_convertible&lt;V&amp;&amp;, T&gt;::value</code> is <code>true</code>.</p></dd>
    <dt>Returns:</dt> <dd><p><code><var>op</var> ? *<var>op</var> : static_cast&lt;T&gt;(std::forward&lt;V&gt;(<var>v</var>))</code>.</p></dd>
  </dl>
  
  
  <p class="function">
  <code>template &lt;class T, class V&gt;<br>
    &nbsp;&nbsp;typename decay&lt;T&gt;::type get_value_or(optional&lt;T&gt;&amp;&amp; <var>op</var>, V&amp;&amp; <var>v</var>);</code>
  </p>

  <dl class="attribute">
    <dt>Requires:</dt> <dd><p><code>is_move_constructible&lt;T&gt;::value</code> is <code>true</code> and <code>is_convertible&lt;V&amp;&amp;, T&gt;::value</code> is <code>true</code>.</p></dd>

    <dt>Returns:</dt> <dd><p><code><var>op</var> ? std::move(*<var>op</var>) : static_cast&lt;T&gt;(std::forward&lt;V&gt;(<var>v</var>))</code>.</p></dd>
    <dt>Remarks:</dt> <dd><p>This function provides the same exception safety as <code>T</code>'s move-constructor.</p></dd>
  </dl>
  
  
  <p class="function">
  <code>template &lt;class T&gt;<br>
    &nbsp;&nbsp;optional&lt;<em>V</em>&gt; make_optional(T&amp;&amp; <var>v</var>);</code>
  </p>
  
  <dl class="attribute">
    <dt>Returns:</dt> <dd><p><code>optional&lt;<em>V</em>&gt;(std::forward&lt;T&gt;(<var>v</var>))</code>, <br>where <code><var>V</var></code> is defined as <code><em>X</em>&amp;</code> if <code>T</code> equals <code>reference_wrapper&lt;X&gt;</code>; otherwise <code><var>V</var></code> is <code>typename decay&lt;T&gt;::type</code>.</p></dd>
  </dl>
  
  
 
</blockquote>


<h2><a name='implementability'>Implementability</a></h2>


<p>This proposal can be implemented as pure library extension, without any compiler magic support, in C++11. Below we perovide a reference implementation that has been tested in GCC 4.6.3 and Clang 3.2.</p>


<h3><a name='implementability.refimpl'>Reference implementation</a></h3>

<!--BEG-->
<pre>
# include &lt;utility&gt;
# include &lt;type_traits&gt;
# include &lt;initializer_list&gt;
# include &lt;cassert&gt;

# define REQUIRES(...) typename enable_if&lt;__VA_ARGS__::value, bool&gt;::type = false


namespace std{


// workaround for missing traits in GCC and CLANG
template &lt;class T&gt;
struct is_nothrow_move_constructible
{
  constexpr static bool value = std::is_nothrow_constructible&lt;T, T&amp;&amp;&gt;::value;
};


template &lt;class T, class U&gt;
struct is_assignable
{
  template &lt;class X, class Y&gt;
  static constexpr bool has_assign(...) { return false; }

  template &lt;class X, class Y, size_t S = sizeof(std::declval&lt;X&gt;() = std::declval&lt;Y&gt;()) &gt;
  static constexpr bool has_assign(bool) { return true; }

  constexpr static bool value = has_assign&lt;T, U&gt;(true);
};


template &lt;class T&gt;
struct is_nothrow_move_assignable
{
  template &lt;class X, bool has_any_move_massign&gt;
  struct has_nothrow_move_assign {
    constexpr static bool value = false;
  };

  template &lt;class X&gt;
  struct has_nothrow_move_assign&lt;X, true&gt; {
    constexpr static bool value = noexcept( std::declval&lt;X&amp;&gt;() = std::declval&lt;X&amp;&amp;&gt;() );
  };

  constexpr static bool value = has_nothrow_move_assign&lt;T, is_assignable&lt;T&amp;, T&amp;&amp;&gt;::value&gt;::value;
};
// end workaround



namespace experimental{


// 20.5.4, optional for object types
template &lt;class T&gt; class optional;

// 20.5.5, optional for lvalue reference types
template &lt;class T&gt; class optional&lt;T&amp;&gt;;


template &lt;class T, class U&gt;
struct is_explicitly_convertible
{
  constexpr static bool value = 
    std::is_constructible&lt;U, T&gt;::value &amp;&amp;
    !std::is_convertible&lt;T, U&gt;::value;
};


template &lt;class U&gt;
struct is_not_optional
{
  constexpr static bool value = true;
};

template &lt;class T&gt;
struct is_not_optional&lt;optional&lt;T&gt;&gt;
{
  constexpr static bool value = false;
};


constexpr struct trivial_init_t{} trivial_init{};


// 20.5.6, In-place construction
constexpr struct emplace_t{} emplace{};


// 20.5.7, Disengaged state indicator
struct nullopt_t
{
  struct init{};
  constexpr nullopt_t(init){};
}; 
constexpr nullopt_t nullopt{nullopt_t::init{}};


template &lt;class T&gt;
union storage_t
{
  unsigned char dummy_;
  T value_;

  constexpr storage_t( trivial_init_t ) : dummy_() {};

  template &lt;class... Args&gt;
  storage_t( Args&amp;&amp;... args ) : value_(std::forward&lt;Args&gt;(args)...) {}
  
  storage_t() : value_() {} // GCC bug workaround

  ~storage_t(){}
};


template &lt;class T&gt;
class optional 
{
  static_assert( !std::is_same&lt;T, nullopt_t&gt;::value, "bad T" );
  static_assert( !std::is_same&lt;T, emplace_t&gt;::value, "bad T" );
  
  bool init_;
  storage_t&lt;T&gt; storage_;

  bool initialized() const noexcept { return init_; }
  T* dataptr() {  return std::addressof(storage_.value_); }
  const T* dataptr() const { return std::addressof(storage_.value_); }
  
  void clear() noexcept { 
    if (initialized()) dataptr()-&gt;T::~T();
    init_ = false; 
  }
  
  template &lt;class... Args&gt;
  void initialize(Args&amp;&amp;... args) noexcept(noexcept(T(std::forward&lt;Args&gt;(args)...)))
  {
    assert(!init_);
    ::new (static_cast&lt;void*&gt;(dataptr())) T(std::forward&lt;Args&gt;(args)...);
    init_ = true;
  }
  
  template &lt;class U, class... Args&gt;
  void initialize(std::initializer_list&lt;U&gt; il, Args&amp;&amp;... args) noexcept(noexcept(T(std::forward&lt;Args&gt;(args)...)))
  {
    assert(!init_);
    ::new (static_cast&lt;void*&gt;(dataptr())) T(il, std::forward&lt;Args&gt;(args)...);
    init_ = true;
  }

public:
  typedef T value_type;

  // 20.5.5.1, constructors
  constexpr optional() noexcept : init_(false), storage_(trivial_init) {};
  constexpr optional(nullopt_t) noexcept : init_(false), storage_(trivial_init) {};

  optional(const optional&amp; rhs) 
  : init_(rhs.initialized())
  {
    if (rhs.initialized()) ::new (static_cast&lt;void*&gt;(dataptr())) T(*rhs);
  }

  optional(optional&amp;&amp; rhs) noexcept(std::is_nothrow_move_constructible&lt;T&gt;::value)
  : init_(rhs.initialized())
  {
    if (rhs.initialized()) ::new (static_cast&lt;void*&gt;(dataptr())) T(std::move(*rhs));
  }

  optional(const T&amp; v) : init_(true), storage_(v) {}

  optional(T&amp;&amp; v) : init_(true), storage_(std::move(v)) {}
<!--  
  template &lt;class U, REQUIRES(is_explicitly_convertible&lt;U, T&gt;)&gt;
  explicit optional(U&amp;&amp; v) : init_(true), storage_(std::forward&lt;U&gt;(v)) {}
  
  template &lt;class U, REQUIRES(is_convertible&lt;U, T&gt;)&gt;
  optional(U&amp;&amp; v) : init_(true), storage_(std::forward&lt;U&gt;(v)) {}
  
  template &lt;class U, REQUIRES(is_explicitly_convertible&lt;U, T&gt;)&gt; 
  explicit optional(const optional&lt;U&gt;&amp; rhs)
  : init_(rhs.initialized())
  {
    if (rhs.initialized()) new (dataptr()) T(*rhs);
  }
  
  template &lt;class U, REQUIRES(is_convertible&lt;U, T&gt;)&gt; 
  optional(const optional&lt;U&gt;&amp; rhs)
  : init_(rhs.initialized())
  {
    if (rhs.initialized()) new (dataptr()) T(*rhs);
  }
  
  template &lt;class U, REQUIRES(is_explicitly_convertible&lt;U, T&gt;)&gt; 
  explicit optional(optional&lt;U&gt;&amp;&amp; rhs)
  : init_(rhs.initialized())
  {
    if (rhs.initialized()) new (dataptr()) T(std::move(*rhs));
  }
  
  template &lt;class U, REQUIRES(is_convertible&lt;U, T&gt;)&gt; 
  optional(optional&lt;U&gt;&amp;&amp; rhs)
  : init_(rhs.initialized())
  {
    if (rhs.initialized()) new (dataptr()) T(std::move(*rhs));
  }
 
  template &lt;class U, REQUIRES(is_explicitly_convertible&lt;std::initializer_list&lt;U&gt;, T&gt;)&gt;
  explicit optional(std::initializer_list&lt;U&gt; il)
  : init_(true), storage_(il) {}
  
  template &lt;class U, REQUIRES(is_convertible&lt;std::initializer_list&lt;U&gt;, T&gt;)&gt;
  optional(std::initializer_list&lt;U&gt; il)
  : init_(true), storage_(il) {}
-->
  template &lt;class... Args&gt; explicit optional(emplace_t, Args&amp;&amp;... args)
  : init_(true), storage_(std::forward&lt;Args&gt;(args)...) {}

  template &lt;class U, class... Args, REQUIRES(is_constructible&lt;T, std::initializer_list&lt;U&gt;&gt;)&gt;
  explicit optional(emplace_t, std::initializer_list&lt;U&gt; il, Args&amp;&amp;... args)
  : init_(true), storage_(il, std::forward&lt;Args&gt;(args)...) {}

  // 20.5.4.2 Destructor 
  ~optional() { if (initialized()) dataptr()-&gt;T::~T(); }

  // 20.5.4.3, assignment
  optional&amp; operator=(nullopt_t) noexcept
  {
    clear();
    return *this;
  }
  
  optional&amp; operator=(const optional&amp; rhs)
  {
    if      (init_ == true  &amp;&amp; rhs.init_ == false) clear();
    else if (init_ == false &amp;&amp; rhs.init_ == true)  initialize(*rhs);
    else if (init_ == true  &amp;&amp; rhs.init_ == true)  *dataptr() = *rhs;
    return *this;
  }
  
  optional&amp; operator=(optional&amp;&amp; rhs) 
  noexcept(std::is_nothrow_move_assignable&lt;T&gt;::value &amp;&amp; std::is_nothrow_move_constructible&lt;T&gt;::value)
  {
    if      (init_ == true  &amp;&amp; rhs.init_ == false) clear();
    else if (init_ == false &amp;&amp; rhs.init_ == true)  initialize(std::move(*rhs));
    else if (init_ == true  &amp;&amp; rhs.init_ == true)  *dataptr() = std::move(*rhs);
    return *this;
  }
 
  template &lt;class U&gt;
  auto operator=(U&amp;&amp; v)
  -&gt; typename enable_if
  &lt;
    is_same&lt;typename remove_reference&lt;U&gt;::type, T&gt;::value,
    optional&amp;
  &gt;::type
  {
    if (initialized()) { *dataptr() = std::forward&lt;U&gt;(v); }
    else               { initialize(std::forward&lt;U&gt;(v));  }  
    return *this;             
  } 
<!--   
  template &lt;class U&gt;
  auto operator=(U&amp;&amp; v)
  -&gt; typename enable_if
  &lt;
        is_not_optional&lt;typename decay&lt;U&gt;::type&gt;::value 
        &amp;&amp; !is_same&lt;nullopt_t,typename decay&lt;U&gt;::type&gt;::value, 
        optional&amp;
  &gt;::type
  {
    if (initialized()) { *dataptr() = std::forward&lt;U&gt;(v); }
    else               { initialize(std::forward&lt;U&gt;(v));  }  
    return *this;             
  }

  template &lt;class U&gt; 
  optional&amp; operator=(const optional&lt;U&gt;&amp; rhs)
  {
    if      (init_ == true  &amp;&amp; rhs.init_ == false) clear();
    else if (init_ == false &amp;&amp; rhs.init_ == true)  initialize(*rhs);
    else if (init_ == true  &amp;&amp; rhs.init_ == true)  *dataptr() = *rhs;
    return *this;
  }
  
  template &lt;class U&gt; 
  optional&amp; operator=(optional&lt;U&gt;&amp;&amp; rhs)
  {
    if      (init_ == true  &amp;&amp; rhs.init_ == false) clear();
    else if (init_ == false &amp;&amp; rhs.init_ == true)  initialize(std::move(*rhs));
    else if (init_ == true  &amp;&amp; rhs.init_ == true)  *dataptr() = std::move(*rhs);
    return *this;
  }
 
  template &lt;class U, REQUIRES(is_assignable&lt;T, std::initializer_list&lt;U&gt;&gt;)&gt;
  optional&amp; operator= (std::initializer_list&lt;U&gt; il) 
  {
    if (initialized()) { *dataptr() = il; }
    else               { new (dataptr()) T(il); init_ = true; }
    return *this;
  }
-->  
  template &lt;class... Args&gt; 
  optional&lt;T&gt;&amp; emplace(Args&amp;&amp;... args)
  {
    clear();
    initialize(std::forward&lt;Args&gt;(args)...);
    return *this;
  }
  
  template &lt;class U, class... Args&gt; 
  optional&lt;T&gt;&amp; emplace(initializer_list&lt;U&gt; il, Args&amp;&amp;... args)
  {
    clear();
    initialize&lt;U, Args...&gt;(il, std::forward&lt;Args&gt;(args)...);
    return *this;
  }
  
  // 20.5.4.4 Swap
  void swap(optional&lt;T&gt;&amp; rhs) noexcept(is_nothrow_move_constructible&lt;T&gt;::value &amp;&amp; noexcept(swap(declval&lt;T&amp;&gt;(), declval&lt;T&amp;&gt;())))
  {
    if      (init_ == true  &amp;&amp; rhs.init_ == false) { rhs.initialize(std::move(**this)); clear(); }
    else if (init_ == false &amp;&amp; rhs.init_ == true)  { initialize(std::move(*rhs)); rhs.clear(); }
    else if (init_ == true  &amp;&amp; rhs.init_ == true)  { using std::swap; swap(**this, *rhs); }
  }

  // 20.5.4.5 Observers 
  T const* operator -&gt;() const { 
    assert (initialized()); 
    return dataptr(); 
  }
  
  T* operator -&gt;() { 
    assert (initialized()); 
    return dataptr(); 
  }
  
  T const&amp; operator *() const { 
    assert (initialized()); 
    return *dataptr();
  }
  
  T&amp; operator *() { 
    assert (initialized()); 
    return *dataptr(); 
  }
  
  explicit operator bool() const noexcept { return initialized(); }  
};


template &lt;class T&gt;
class optional&lt;T&amp;&gt;
{
  static_assert( !std::is_same&lt;T, nullopt_t&gt;::value, "bad T" );
  static_assert( !std::is_same&lt;T, emplace_t&gt;::value, "bad T" );
  T* ref;
  
public:

  // 20.5.5.1, construction/destruction
  constexpr optional() : ref(nullptr) {}
  
  constexpr optional(nullopt_t) : ref(nullptr) {}
   
  optional(T&amp; v) noexcept : ref(&amp;v) {}
  
  optional(T&amp;&amp;) = delete;
  
  optional(const optional&amp; rhs) noexcept : ref(rhs.ref) {}
  
  template &lt;class U&gt; 
  optional(const optional&lt;U&amp;&gt;&amp; rhs) noexcept : ref(rhs.ref) {}
  
  explicit optional(emplace_t, T&amp; v) noexcept : ref(&amp;v) {}
  
  explicit optional(emplace_t, T&amp;&amp;) = delete;
  
  ~optional() = default;
  
  // 20.5.5.2, mutation
  optional&amp; operator=(nullopt_t) noexcept {
    ref = nullptr;
    return *this;
  }
  
  optional&amp; operator=(optional&amp;&amp;) = delete;
  optional&amp; operator=(const optional&amp;) = delete;
  
  optional&amp; emplace(T&amp; v) noexcept {
    ref = &amp;v;
    return *this;
  }
  
  optional&amp; emplace(T&amp;&amp;) = delete;
    
  // 20.5.5.3, observers
  T* operator-&gt;() const {
    assert (ref); 
    return ref;
  }
  
  T&amp; operator*() const {
    assert (ref); 
    return *ref;
  }
  
  explicit operator bool() const noexcept { 
    return ref != nullptr; 
  }  
};


template &lt;class T&gt;
class optional&lt;T&amp;&amp;&gt;
{
  static_assert( sizeof(T) == 0, "optional rvalue referencs disallowed" );
};


// 20.5.8, Relational operators
template &lt;class T&gt; bool operator==(const optional&lt;T&gt;&amp; x, const optional&lt;T&gt;&amp; y)
{
  return bool(x) != bool(y) ? false : bool(x) == false ? true : *x == *y;
}

template &lt;class T&gt; bool operator!=(const optional&lt;T&gt;&amp; x, const optional&lt;T&gt;&amp; y)
{
  return !(x == y);
}

template &lt;class T&gt; bool operator&lt;(const optional&lt;T&gt;&amp; x, const optional&lt;T&gt;&amp; y)
{
  return (!y) ? false : (!x) ? true : *x &lt; *y;
}
  
template &lt;class T&gt; bool operator&gt;(const optional&lt;T&gt;&amp; x, const optional&lt;T&gt;&amp; y)
{
  return (y &lt; x);
}

template &lt;class T&gt; bool operator&lt;=(const optional&lt;T&gt;&amp; x, const optional&lt;T&gt;&amp; y)
{
  return !(y &lt; x);
}

template &lt;class T&gt; bool operator&gt;=(const optional&lt;T&gt;&amp; x, const optional&lt;T&gt;&amp; y)
{
  return !(x &lt; y);
}


// 20.5.9 Comparison with nullopt
template &lt;class T&gt; bool operator==(const optional&lt;T&gt;&amp; x, nullopt_t) noexcept
{
  return (!x);
}

template &lt;class T&gt; bool operator==(nullopt_t, const optional&lt;T&gt;&amp; x) noexcept
{
  return (!x);
}

template &lt;class T&gt; bool operator!=(const optional&lt;T&gt;&amp; x, nullopt_t) noexcept
{
  return bool(x);
}

template &lt;class T&gt; bool operator!=(nullopt_t, const optional&lt;T&gt;&amp; x) noexcept
{
  return bool(x);
}

template &lt;class T&gt; bool operator&lt;(const optional&lt;T&gt;&amp;, nullopt_t) noexcept
{
  return false;
}

template &lt;class T&gt; bool operator&lt;(nullopt_t, const optional&lt;T&gt;&amp; x) noexcept
{
  return bool(x);
}

template &lt;class T&gt; bool operator&lt;=(const optional&lt;T&gt;&amp; x, nullopt_t) noexcept
{
  return (!x);
}

template &lt;class T&gt; bool operator&lt;=(nullopt_t, const optional&lt;T&gt;&amp;) noexcept
{
  return true;
}

template &lt;class T&gt; bool operator&gt;(const optional&lt;T&gt;&amp; x, nullopt_t) noexcept
{
  return bool(x);
}

template &lt;class T&gt; bool operator&gt;(nullopt_t, const optional&lt;T&gt;&amp;) noexcept
{
  return false;
}

template &lt;class T&gt; bool operator&gt;=(const optional&lt;T&gt;&amp;, nullopt_t) noexcept
{
  return true;
}

template &lt;class T&gt; bool operator&gt;=(nullopt_t, const optional&lt;T&gt;&amp; x) noexcept
{
  return (!x);
}


// 20.5.10 Poisoned comparison with T
template &lt;class T&gt; void operator==(const optional&lt;T&gt;&amp;, const T&amp;) noexcept
{
    static_assert(sizeof(T) == 0, "comparison between optional&lt;T&gt; and T disallowed");
}

template &lt;class T&gt; void operator==(const T&amp;, const optional&lt;T&gt;&amp;) noexcept
{
    static_assert(sizeof(T) == 0, "comparison between optional&lt;T&gt; and T disallowed");
}

template &lt;class T&gt; void operator!=(const optional&lt;T&gt;&amp;, const T&amp;) noexcept
{
    static_assert(sizeof(T) == 0, "comparison between optional&lt;T&gt; and T disallowed");
}

template &lt;class T&gt; void operator!=(const T&amp;, const optional&lt;T&gt;&amp;) noexcept
{
    static_assert(sizeof(T) == 0, "comparison between optional&lt;T&gt; and T disallowed");
}

template &lt;class T&gt; void operator&lt;(const optional&lt;T&gt;&amp;, const T&amp;) noexcept
{
    static_assert(sizeof(T) == 0, "comparison between optional&lt;T&gt; and T disallowed");
}

template &lt;class T&gt; void operator&lt;(const T&amp;, const optional&lt;T&gt;&amp;) noexcept
{
    static_assert(sizeof(T) == 0, "comparison between optional&lt;T&gt; and T disallowed");
}

template &lt;class T&gt; void operator&lt;=(const optional&lt;T&gt;&amp;, const T&amp;) noexcept
{
    static_assert(sizeof(T) == 0, "comparison between optional&lt;T&gt; and T disallowed");
}

template &lt;class T&gt; void operator&lt;=(const T&amp;, const optional&lt;T&gt;&amp;) noexcept
{
    static_assert(sizeof(T) == 0, "comparison between optional&lt;T&gt; and T disallowed");
}

template &lt;class T&gt; void operator&gt;(const optional&lt;T&gt;&amp;, const T&amp;) noexcept
{
    static_assert(sizeof(T) == 0, "comparison between optional&lt;T&gt; and T disallowed");
}

template &lt;class T&gt; void operator&gt;(const T&amp;, const optional&lt;T&gt;&amp;) noexcept
{
    static_assert(sizeof(T) == 0, "comparison between optional&lt;T&gt; and T disallowed");
}

template &lt;class T&gt; void operator&gt;=(const optional&lt;T&gt;&amp;, const T&amp;) noexcept
{
    static_assert(sizeof(T) == 0, "comparison between optional&lt;T&gt; and T disallowed");
}

template &lt;class T&gt; void operator&gt;=(const T&amp;, const optional&lt;T&gt;&amp;) noexcept
{
    static_assert(sizeof(T) == 0, "comparison between optional&lt;T&gt; and T disallowed");
}


// 20.5.11 Specialized algorithms 
template &lt;class T&gt; 
void swap(optional&lt;T&gt;&amp; x, optional&lt;T&gt;&amp; y) noexcept(noexcept(x.swap(y)))
{
  static_assert(!is_reference&lt;T&gt;::value, "no swap for optional refs");
  x.swap(y);
}

template &lt;class T, class V&gt;
typename decay&lt;T&gt;::type get_value_or(const optional&lt;T&gt;&amp; op, V&amp;&amp; v)
{
  return op ? *op : static_cast&lt;T&gt;(std::forward&lt;V&gt;(v));
}

template &lt;class T, class V&gt;
typename decay&lt;T&gt;::type get_value_or(optional&lt;T&gt;&amp;&amp; op, V&amp;&amp; v)
{
  return op ? std::move(*op) : static_cast&lt;T&gt;(std::forward&lt;V&gt;(v));
}

template &lt;class T&gt;
optional&lt;typename decay&lt;T&gt;::type&gt; make_optional(T&amp;&amp; v)
{
  return optional&lt;typename decay&lt;T&gt;::type&gt;(std::forward&lt;T&gt;(v));
}

template &lt;class X&gt;
optional&lt;X&amp;&gt; make_optional(reference_wrapper&lt;X&gt; v)
{
  return optional&lt;X&amp;&gt;(v);
}


} // namespace experimental
} // namespace std
</pre>
<!--END-->

<h2><a name='acknowledgements'>Acknowledgements</a></h2>

<p>Many people from the Boost community, participated in the developement of the Boost.Optional library. Sebastian Redl suggested the usage of function <code>emplace</code>. </p>

<p>Daniel Kr&uuml;gler provided numerous helpful suggestions, corrections and comments on this paper; in particular he suggested the addition of and reference implementation for "perfect initialization" operations.</p>

<p>People in discussion group "ISO C++ Standard - Future Proposals" provided numerous insightful suggestions: Vladimir Batov (who described and supported the perfect forwarding constructor), Nevin Liber, Ville Voutilainen, Richard Smiths, Dave Abrahams, Chris Jefferson, Jeffrey Yasskin, Nikolay Ivchenkov, and many more. </p>

<h2><a name='literature'>References</a></h2>

<ol>
<li>John J. Barton, Lee R. Nackman, "Scientific and Engineering C++: An Introduction with Advanced Techniques and Examples".</li>

<li>Fernando Cacciola, Boost.Optional library (<a href='http://www.boost.org/doc/libs/1_49_0/libs/optional/doc/html/index.html'>http://www.boost.org/doc/libs/1_49_0/libs/optional/doc/html/index.html</a>)</li>

<li>MSDN Library, "Nullable Types (C# Programming Guide)", (<a href='http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx'>http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx</a></li>

<li>Code Synthesis Tools, "C++ Object Persistence with ODB", (<a href='http://www.codesynthesis.com/products/odb/doc/manual.xhtml#7.3'>http://www.codesynthesis.com/products/odb/doc/manual.xhtml#7.3</a>)</li>

<li>Jaakko J&auml;rvi, Boost Tuple Library (<a href="http://www.boost.org/doc/libs/1_49_0/libs/tuple/doc/tuple_users_guide.html">http://www.boost.org/doc/libs/1_49_0/libs/tuple/doc/tuple_users_guide.html</a>) </li>

<li>Alisdair Meredith, John Lakos, "<code>noexcept</code> Prevents Library Validation" (N3248, <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3248.pdf">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3248.pdf</a>)</li>

<li>Walter E. Brown, "A Preliminary Proposal for a Deep-Copying Smart Pointer" (N3339, <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3339.pdf">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3339.pdf</a>)</li>
</ol>



  

</body>
</html>
