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

标签 c++ c++11

我知道以下问题:C++11 lambdas: member variable capture gotcha。此外,我知道需要通过捕获 this 指针来捕获类成员,正如这个问题的答案所明确指出的那样。

Yes. Capturing member variables is always done via capturing this; it is the only way to access a member variable.

但是,捕获this 指针捕获所有类成员。是否可以限制捕获哪些类(class)成员?例如,是否可以捕获单个类成员

我知道以下方法行不通,但有可能实现吗?

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

来自评论:

Why do you need this?

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

最佳答案

使用 C++11,您将必须捕获 this

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

[mBar1 = this->mBar1]() { ... }

或引用:

[&mBar1 = this->mBar1]() { ... }

关于c++ - 如何在 lambda 表达式中捕获单个类数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30653624/

相关文章:

c++ - 指定算法的输入和输出范围

c++ - Visual Studio 无法在 Release模式下显示 'this' 的值(带有调试信息)

c++ - 十进制转十六进制,找不到我的逻辑错误

c++ - 将 uint8_t 数组转换为字符串

c++ - 在 C++ 11 中将 `nullptr` 作为 `std::shared_ptr` 返回是否安全?

c++ - 当模板类型是基本类型时通过引用传递的成本

c++ - CMake find_package 可以是 "common dependency version aware"吗?

c++ - 混合 Objective-C 和 C++ 代码

c++ - 为什么这段代码在 Clang++ 中有效,但在 G++ 中无效?

c++ - 实现昂贵的 C++ 迭代器