如何在lambda表达式中捕获单个类数据成员?

Jam*_*son 5 c++ c++11

我知道以下问题:C++ 11 lambdas:成员变量捕获陷阱.此外,我知道需要通过捕获this指针捕获类成员,因为这个问题的答案清楚地说明了.

是.捕获成员变量总是通过捕获它来完成; 它是访问成员变量的唯一方法.

但是,捕获this指针会捕获所有类成员.是否可以限制捕获哪些班级成员?例如,是否可以捕获单个类成员

我知道以下不起作用但是有可能实现吗?

class Foo
{
public:
    Foo() : mBar1(1), mBar2(2) {}

    void doBar()
    {
        auto test = [this->mBar1]()
            {
                std::cout << mBar1 << "\n";
                // Trying to access 'mBar2' here would fail to compile...
            };

        test();
    }

    int mBar1;
    int mBar2;
};
Run Code Online (Sandbox Code Playgroud)

来自评论:

你为什么需要这个?

不需要这样做.我只是想知道这是否可行,如果可行,怎么做.

Bri*_*ian 13

使用C++ 11,你将不得不捕获this.

但是,在C++ 14中,您可以通过值捕获任意表达式:

[mBar1 = this->mBar1]() { ... }
Run Code Online (Sandbox Code Playgroud)

或参考:

[&mBar1 = this->mBar1]() { ... }
Run Code Online (Sandbox Code Playgroud)


R S*_*ahu 7

如果您能够使用C++ 14编译器,则可以使用

auto test = [&bar = this->mBar1]()
{
    std::cout << bar<< "\n";
};
Run Code Online (Sandbox Code Playgroud)

如果您只能使用C++ 11编译器,则必须捕获this.