vendredi 28 juin 2019

Deducing Lambda Capture Types

I've recently found that capturing a const object by value in a lambda, implies that the variable inside the labmda's body (i.e. the lambda's data member) is also const.
For example:

const int x = 0;
auto foo = [x]{
  // x is const int
};

This behavior is mentioned in § 8.1.5.2 in the draft for C++17:

For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The declaration order of these members is unspecified. The type of such a data member is the referenced type if the entity is a reference to an object, an lvalue reference to the referenced function type if the entity is a reference to a function, or the type of the corresponding captured entity otherwise. A member of an anonymous union shall not be captured by copy.

I would expect that deducing type of captured variables will be the same as deducing auto.
Is there a good reason for having different type-deduction rules for captured types?

Aucun commentaire:

Enregistrer un commentaire