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
.
在下面的示例中,我可以从lambda y中访问constexpr变量x,而无需显式地捕获它。如果x没有声明为constexpr,这是不可能的。
Are there special rules that apply to constexpr
for capturing?
对于constexpr是否有适用于捕获的特殊规则?
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);
}
1 个解决方案
#1
32
Are there special rules that apply to
constexpr
for capturing/accessing?constexpr中是否有用于捕获/访问的特殊规则?
Yes, constexpr
variables could be read without capturing in lambda:
是的,constexpr变量可以不用lambda来读取:
A lambda expression can read the value of a variable without capturing it if the variable
lambda表达式可以读取变量的值,而不捕获变量的值
- has const non-volatile integral or enumeration type and has been initialized with a constant expression, or
- const是否具有非易失性积分或枚举类型,并已用常量表达式初始化
- is constexpr and trivially copy constructible.
- 是可构造的。
#1
32
Are there special rules that apply to
constexpr
for capturing/accessing?constexpr中是否有用于捕获/访问的特殊规则?
Yes, constexpr
variables could be read without capturing in lambda:
是的,constexpr变量可以不用lambda来读取:
A lambda expression can read the value of a variable without capturing it if the variable
lambda表达式可以读取变量的值,而不捕获变量的值
- has const non-volatile integral or enumeration type and has been initialized with a constant expression, or
- const是否具有非易失性积分或枚举类型,并已用常量表达式初始化
- is constexpr and trivially copy constructible.
- 是可构造的。