title: Get underlying type of any C++ dereferencable type
body: <p>I have a function that creates a new object of the underlying type of <code>P</code>. Here <code>P</code> is a dereferencable type like a pointer or a smart pointer.</p>
  
  <pre class="lang-cpp prettyprint-override"><code>template&lt;typename P&gt;
  auto make_new()
  </code></pre>
  
  <p>For example, for pointers and smart pointers, </p>
  
  <pre class="lang-cpp prettyprint-override"><code>struct A
  {
      int a = 3;
  };
  
  A* a = make_new&lt;A*&gt;();
  std::cout &lt;&lt; a-&gt;a &lt;&lt; std::endl;
  delete a;
  
  std::shared_ptr&lt;A&gt; b = make_new&lt;std::shared_ptr&lt;A&gt;&gt;();
  std::cout &lt;&lt; b-&gt;a &lt;&lt; std::endl;
  </code></pre>
  
  <p>Now, for shared pointers, I would implement <code>make_new</code> as the following, </p>
  
  <pre class="lang-cpp prettyprint-override"><code>template&lt;typename P&gt;
  auto make_new()
  {
      using Ptype = typename P::element_type;
      return P(new Ptype);
  }
  </code></pre>
  
  <p>which doesn't work for pointers. </p>
  
  <p>Now, something that works for both pointers and smart pointers,</p>
  
  <pre class="lang-cpp prettyprint-override"><code>template&lt;typename P&gt;
  auto make_new()
  {
      using Ptype = typename std::remove_reference&lt;decltype(*P())&gt;::type;
      return P(new Ptype);
  }
  </code></pre>
  
  <p>but doesn't work for <code>std::optional</code>.</p>
  
  <p>Is there a canonical way of getting the underlying type of a de-referencable object? </p>
  
  <p>I know that <code>*</code> and <code>-&gt;</code> can be overloaded to anything and there is no guarantee that constructor works like above, or makes sense to do.</p>
  
  <p>Just want to know if there is a way and am not just finding it, or just doing something dumb.</p>