Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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.

like image 516
James Adkison Avatar asked Jun 04 '15 20:06

James Adkison


2 Answers

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]() { ... }
like image 73
Brian Bi Avatar answered Sep 21 '22 17:09

Brian Bi


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.

like image 32
R Sahu Avatar answered Sep 21 '22 17:09

R Sahu