Access to constexpr variable inside lambda expression without capturing

孤街醉人 提交于 2019-12-21 03:10:50

问题


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

回答1:


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.


来源:https://stackoverflow.com/questions/50247190/access-to-constexpr-variable-inside-lambda-expression-without-capturing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!