Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could make use of lambdas for such cases:</p> <pre><code> const int x = []() -&gt; int { int t; std::cin &gt;&gt; t; return t; }(); </code></pre> <p>(Note the extra () at the end).</p> <p>Instead of writing a separate functions, this has the advantage of not having to jump around in your source file, when reading the code.</p> <p><s><strong>Edit:</strong> Since in the comments it was stated that this goes against the DRY rule, you could take advantage of <code>auto</code> and <code>5.1.2:4</code> to reduce type repetition:</p> <p><code>5.1.2:4</code> states:</p> <blockquote> <p>[...] If a lambda-expression does not include a trailing-return-type, it is as if the trailing-return-type denotes the following type:</p> <ul> <li><p>if the compound-statement is of the form</p> <p><code>{ attribute-specifier-seq(opt) return expression ; }</code></p> <p>the type of the returned expression after lvalue-to-rvalue conversion (4.1), array-to-pointer conversion (4.2), and function-to-pointer conversion (4.3);</p></li> <li><p>otherwise, void.</p></li> </ul> </blockquote> <p>So we could alter the code to look like this:</p> <pre><code> const auto x = [] { int t; std::cin &gt;&gt; t; return t; }(); </code></pre> <p>I can't decide if that is better though, since the type is now "hidden" within the lambda body...</s></p> <p><strong>Edit 2:</strong> In the comments it was pointed out, that just removing the type name where it is possible, does not result in a "DRY-correct" code. Also the trailing-return-type deduction in this case is currently actually an extension of MSVC++ as well as g++ and not (yet) standard.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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