In the following example, I can access the constexpr
variable x
from inside the lambda y
without explicitly capturing it. This is not possible if x
is not declared as constexpr
.
Are there special rules that apply to constexpr
for capturing?
int foo(auto l) {
// OK
constexpr auto x = l();
auto y = []{return x;};
return y();
// NOK
// auto x2 = l();
// auto y2 = []{ return x2; };
// return y2();
}
auto l2 = []{return 3;};
int main() {
foo(l2);
}
Lambdas are now allowed inside constexpr functions.
A constexpr variable must be initialized at compile time. All constexpr variables are const . A variable can be declared with constexpr , when it has a literal type and is initialized. If the initialization is performed by a constructor, the constructor must be declared as constexpr .
Lambdas always capture objects, and they can do so by value or by reference.
The lambda is capturing an outside variable. A lambda is a syntax for creating a class. Capturing a variable means that variable is passed to the constructor for that class. A lambda can specify whether it's passed by reference or by value.
A Lambda expression has access to both instance and static variables of it's enclosing class and also it can access local variables which are effectively final or final.
A lambda is implicitly constexpr if its result satisfies the requirements of a constexpr function: If a lambda is implicitly or explicitly constexpr, and you convert it to a function pointer, the resulting function is also constexpr:
Enclosed variables can be used at any place in Lambda but the value can not be changed. 4. Conclusion In this tutorial, We've seen how to access the variables in Lambda Expressions. Learned the behavior inside and outside declaring the variables.
constexpr lambda expressions in C++. Visual Studio 2017 version 15.3 and later (available with /std:c++17): A lambda expression may be declared as constexpr or used in a constant expression when the initialization of each data member that it captures or introduces is allowed within a constant expression.
Are there special rules that apply to
constexpr
for capturing/accessing?
Yes, constexpr
variables could be read without capturing in lambda:
A lambda expression can read the value of a variable without capturing it if the variable
- has const non-volatile integral or enumeration type and has been initialized with a constant expression, or
- is constexpr and trivially copy constructible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With