Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why lambda removes cv and ref?

Given a lambda:

auto f = [](const T& var){ return var; };

Why return type of f is T (not const T&)? Where is this in the Standard?

like image 932
vladon Avatar asked Oct 21 '16 08:10

vladon


1 Answers

The point is:

  1. The use of auto for return type deduction employ template type deduction rule.
  2. The return type is delcared as passed-by-value; which means that the reference-ness and top-level cv-qualifiers of expression used for deduction (i.e. var) are ignored.

Quotes from the standard:

About auto:

If the placeholder is the auto type-specifier, the deduced type T' replacing T is determined using the rules for template argument deduction. Obtain P from T by replacing the occurrences of auto with either a new invented type template parameter U or, if the initialization is copy-list-initialization, with std::initializer_list. Deduce a value for U using the rules of template argument deduction from a function call ([temp.deduct.call]), where P is a function template parameter type and the corresponding argument is e. If the deduction fails, the declaration is ill-formed. Otherwise, T' is obtained by substituting the deduced U into P.

About the rule of template argument deduction from a function call:

If P is not a reference type:

  • If A is a cv-qualified type, the top-level cv-qualifiers of A's type are ignored for type deduction.

About reference:

If an expression initially has the type “reference to T” ([dcl.ref], [dcl.init.ref]), the type is adjusted to T prior to any further analysis.

So for var(i.e. A) is const T&, the deduced return type would be T here.

like image 148
songyuanyao Avatar answered Oct 12 '22 22:10

songyuanyao