James Adkison
James Adkison

Reputation: 9602

How to capture a single class data member in a lambda expression?

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.

Upvotes: 8

Views: 3199

Answers (2)

Brian Bi
Brian Bi

Reputation: 119069

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]() { ... }

Upvotes: 20

R Sahu
R Sahu

Reputation: 206567

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.

Upvotes: 7

Related Questions