I'm aware of the following question: C++11 lambdas: member variable capture gotcha. Furthermore, I'm aware of the need to capture class members by capturing the this
pointer, as the answer to this question clearly states.
Yes. Capturing member variables is always done via capturing this; it is the only way to access a member variable.
However, capturing the this
pointer captures all class members. Is it possible to restrict which class members are captured? For example, is is possible to capture a single class member?
I know the following doesn't work but is it possible to achieve?
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;
};
From the comments:
Why do you need this?
I don't need to do this. I'm just curious about understanding whether this is possible and if so how to do it.
Using C++11 you will have to capture this
.
However, in C++14 you can capture arbitrary expressions, either by value:
[mBar1 = this->mBar1]() { ... }
or reference:
[&mBar1 = this->mBar1]() { ... }
If you are able to use a C++14 compiler, you can use
auto test = [&bar = this->mBar1]()
{
std::cout << bar<< "\n";
};
If you are restricted to using a C++11 compiler, you'll have to capture this
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With