Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you are simply trying to set the return type, make it a template argument. This way you can change everything related to the return type without actually changing the function. You can put a default return type if you want like in this example.</p> <pre><code>template &lt;class R = int, class T&gt; R f(T&amp;&amp; x) { ... return h2(y2, y3); } </code></pre> <hr> <p>The code below demonstrates it's effectiveness.</p> <p><strong>DEMO CODE:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; template &lt;class T, class S&gt; T h2(T&amp; x, S&amp; y) { return x + y; } template &lt;class R = int, class T&gt; R f(T&amp; x) { auto y2 = x; auto y3 = x; return h2(y2, y3); } int main(int argc, char** argv) { int x = 7; std::string str = "test! "; auto d = f&lt;double&gt;(x); auto i = f(x); // use default type (int) auto s = f&lt;std::string&gt;(str); std::cout &lt;&lt; std::fixed &lt;&lt; std::setprecision(4); std::cout &lt;&lt; "double: " &lt;&lt; d &lt;&lt; std::endl; std::cout &lt;&lt; "int: " &lt;&lt; i &lt;&lt; std::endl; std::cout &lt;&lt; "string: " &lt;&lt; s &lt;&lt; std::endl; return 0; } </code></pre> <hr> <p><strong>OUTPUT:</strong></p> <pre><code>double: 14.0000 int: 14 string: test! test! </code></pre> <hr> <p>Unfortunately, the exact functionality you are looking for does not exist (yet) and is not part of the C++0x spec. However, it is possible this may be part of the C++1x spec when it is drafted. until then, stick to templates.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

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

Reload