title: Target-typing in modern C++
body: <p>When I say target-typing I mean using the type of the receiver variable or parameter as information to infer parts of the code I'm assigning to it. Like for example, in C# you'd write something like this to pass a nullable value or a <code>null</code> (empty) if necessary:</p>
  <pre class="lang-cs prettyprint-override"><code>void f(int? i) {}
  void caller(bool b) =&gt; 
      f(b ? 5 : null);  // value is bound to an int? parameter so all information 
                        // to build this object is already in code
  </code></pre>
  <p>The best I could come up with in C++ is something like this:</p>
  <pre class="lang-cpp prettyprint-override"><code>void f(const optional&lt;int&gt;&amp; i) {}
  void caller(bool b)
  {
      f(b ? make_optional(5) : optional&lt;int&gt;());
  }
  </code></pre>
  <p>And it works, but it requires me to write <code>optional</code> twice and provide the optional type once, even though all the information should already be in code. This is, in my humble opinion, what type inference should do for you without having to repeat yourself multiple times per line. And because the following does work:</p>
  <pre class="lang-cpp prettyprint-override"><code>optional&lt;int&gt; i;
  i = {};  // empty
  i = {5}; // a value
  </code></pre>
  <p>I'd have thought that the next logical step would also work:</p>
  <pre class="lang-cpp prettyprint-override"><code>void f(const optional&lt;int&gt;&amp; i) {}
  void caller(bool b)
  {
      f(b ? {5} : {});  // doesn't compile
  }
  </code></pre>
  <p>So overall from various experiments it seems target-typing works when directly assigning a value to a variable, but not as part of a ternary conditional expression bound to a parameter? Am I understanding this correctly? There is no limit on the C++ version, I've been writing this in MS C++20 for instance.</p>
  <p>And a related question, though not the main focus of my question, is there a better way of writing an <code>optional&lt;&gt;</code> initialization that can either have a value or not based on a boolean?</p>