我知道以下问题: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/