为什么数据成员不能在Lambda捕获列表中 [英] Why can't a data member be in a lambda capture list

查看:118
本文介绍了为什么数据成员不能在Lambda捕获列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 foo 类,该类具有 bar 作为成员变量。

I have a class foo that has bar as a member variable.

在该类的另一个成员函数中,我正在编写一个lambda函数:

In another member function of the class, I'm writing a lambda function:

[bar](void){}

但是我不能包含 bar 在捕获列表中。为什么会这样呢?

But I can't include bar in the capture list. Why is that?

推荐答案

您可以通过在其中说 this 捕获列表。这与成员是 const 无关。

You capture class members by saying this in the capture list. This has nothing to do with the fact that the member is const.

示例:

#include <iostream>

struct Foo
{
    const int a = 0;
    int b;
    Foo() : b{42} {
        auto f = [this]() { std::cout << a << " " << b << std::endl; };
//                ^^^^ 
        f();
    }
};

int main() {
    Foo x;
}

这篇关于为什么数据成员不能在Lambda捕获列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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