Capturing only a specific member of a class inside lambda

I understand that we have to capture the *this pointer in the lambda to access any of the member variables inside the lambda. Now, why can't I capture only a single member of an object inside the lambda?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>

class Foo
{
public:
    Foo () : a(5) {}
    void func ()
    {
        [this->a] () { std::cout << a; } ();
    }

private:
        int a;
};

int main()
{
    Foo f;
    f.func();
}


This code above throws me a syntax error,

Compiler stderr
<source>: In member function 'void Foo::func()':
<source>:9:14: error: expected ',' before '->' token
9 | [this->a] () { std::cout << a; } ();
| ^~
<source>:9:14: error: expected identifier before '->' token

I tried this in godbolt. org with gcc 11.1
Last edited on
Just capture [this]. The 'a' will be available.

I am no expert on lambdas, so I cannot explain why. But it only took me 30 seconds in C++ Shell to figure it out.
You can do this (I think it's C++17?)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

class Foo
{
public:
	Foo() : a(5) {}

	void func()
	{
		[&a = this->a] () { std::cout << a; } ();
	}

private:
	int a;
};

int main()
{
	Foo f;
	f.func();
}

Last edited on
Topic archived. No new replies allowed.