在不捕获的情况下访问lambda表达式内的constexpr变量 [英] Access to constexpr variable inside lambda expression without capturing

查看:87
本文介绍了在不捕获的情况下访问lambda表达式内的constexpr变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,我可以从lambda y内部访问constexpr变量x,而无需显式捕获它.如果未将x声明为constexpr,则这是不可能的.

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.

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);
}

推荐答案

constexpr是否有适用于捕获/访问的特殊规则?

Are there special rules that apply to constexpr for capturing/accessing?

是的,可以在不捕获 lambda constexpr变量的情况>:

Yes, constexpr variables could be read without capturing in lambda:

lambda表达式可以读取变量的值而无需捕获 如果是变量

A lambda expression can read the value of a variable without capturing it if the variable

  • 具有const非易失性整数或枚举类型,并且已使用常量表达式进行了初始化,或者
  • 是constexpr,可轻松复制构造.

这篇关于在不捕获的情况下访问lambda表达式内的constexpr变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆